[matlab] 17.网格矩阵

生成网格矩阵,并且根据条件筛选,重新赋值为0,1二值图像

clear all;close all;
%生成二值图
index= randperm(2500,1000);  %生成10个不重复随机指标
Z= ones(50,50); %默认白底
Z(index) = 0; %随机指标处黑底
imagesc(Z); 

cmap = [0 0 0;1 1 1]; %自定义一个colormap
colormap(cmap);
axis square;
方法1

n=5;%方阵行列数
c=10;%填充c个方格
t = zeros(1,n*n);
list = randperm(n*n);%生成随机数,不重复
list = list(1:c);%取前c个
t(list) = 1;%填充
t = reshape(t,[n n])
m=5;v=5;
for x=1:m
    for y=1:v
        if t(x,y)==1
            fx=[x-1,x-1,x,x];
            fy=[y-1,y,y,y-1];
            fill(fx,fy,'k');
            %fill将点[x1,y1],[x2,y2],[x3,y3],[x4,y4]按序连线,后形成的图像进行填充,参数‘g’表示绿色。
            %[x1,y1],[x2,y2],[x3,y3],[x4,y4]对应写成[x1 x2 x3 x4][y1 y2 y3 y4],hold on表示画在一幅图上。
            hold on
        else
        end
    end
end
[x,y]=meshgrid(0:5); %产生网格数据。
plot(x,y,'k',y,x,'k'); %画横线,画竖线。
axis equal; % 保证网格是方格。
axis([0 5 0 5]); %设置显示范围。
set(gca,'xtick',[1:5]);
set(gca,'ytick',[1:5]);
grid on
grid minor
方法2

clc
clear
close all;

n=10;%方阵行列数
c=10;%填充c个方格
cmap = [0 0 0;1 1 1]; %自定义一个colormap
indic = randperm(n*n,c);  %生成10个不重复随机指标
img = ones(n,n); 
img(indic) = 0;
imagesc(img);
colormap(cmap);
[x,y]=meshgrid(0.5:n+0.5); %产生网格数据。
hold on
plot(x,y,'k',y,x,'k'); %画横线,画竖线。
set(gca, 'XTick',1:n, 'YTick',1:n);
hold off
方法3

figure
x=[1 2 2 1;4 5 5 4;22 23 23 22;44 45 45 44]; %每一行就是黑方块的四个顶点x坐标
y=[4 4 5 5;11 11 12 12;30 30 31 31;7 7 8 8]; %每一行就是黑方块的四个顶点y坐标
for i=1:size(x,1)
fill(x(i,:),y(i,:),'k') %以行为单位进行黑色填充
hold on
end
grid on
xlim([1 50])
ylim([1 50])
set(gca,'xtick',[1:1:50])
set(gca,'ytick',[1:1:50])
方法四 filled

原文地址:https://www.cnblogs.com/clemente/p/9597286.html