资源描述:
《矩阵分块标记》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、%建立一个8*8的随机矩阵,将其2值化为01矩阵%将其分块并进行标记属于同一块的元素用相同的数字标记%分块的规则是只要这个1上下左右有相连的1就算作一块整体%------------------------------------------------------%下面这个函数用于判断这个1的位置,判断出来之后再判断他的周边有没有1,有的话分别将%这坐标存储%所以首先建立这么一个函数文件function[b,c]=xianglian(b,i,j,k)%UNTITLED2Summaryofthisfunctiongoeshere%Detailedexplanationgoesherec
2、=[];b(i,j)=k;ifi+1~=9&&j+1~=9ifi-1~=0&&j-1~=0ifb(i-1,j)==1c=[c;[i-1,j]];endifb(i,j-1)==1c=[c;[i,j-1]];endifb(i+1,j)==1c=[c;[i+1,j]];endifb(i,j+1)==1c=[c;[i,j+1]];endendifi-1==0&&j-1~=0ifb(i,j-1)==1c=[c;[i,j-1]];endifb(i+1,j)==1c=[c;[i+1,j]];endifb(i,j+1)==1c=[c;[i,j+1]];endendifi-1~=0&&j-1==0ifb
3、(i-1,j)==1c=[c;[i-1,j]];endifb(i+1,j)==1c=[c;[i+1,j]];endifb(i,j+1)==1c=[c;[i,j+1]];endendifi-1==0&&j-1==0ifb(i+1,j)==1c=[c;[i+1,j]];endifb(i,j+1)==1c=[c;[i,j+1]];endendendifi+1==9&&j+1~=9ifj-1~=0ifb(i-1,j)==1c=[c;[i-1,j]];endifb(i,j-1)==1c=[c;[i,j-1]];endifb(i,j+1)==1c=[c;[i,j+1]];endendifj-1==
4、0ifb(i-1,j)==1c=[c;[i-1,j]];endifb(i,j+1)==1c=[c;[i,j+1]];endendendifi+1~=9&&j+1==9ifi-1~=0ifb(i-1,j)==1c=[c;[i-1,j]];endifb(i,j-1)==1c=[c;[i,j-1]];endifb(i+1,j)==1c=[c;[i+1,j]];endendifi-1==0ifb(i,j-1)==1c=[c;[i,j-1]];endifb(i+1,j)==1c=[c;[i+1,j]];endendendifi+1==9&&j+1==9ifb(i,j-1)==1c=[c;[i,j
5、-1]];endifb(i-1,j)==1c=[c;[i-1,j]];endendend%---------------------------------------------------%--------------------------------------------------%下面是将连在一块的1全部标记为相同的数字,用到了函数递归调用function[b]=kuai(b,i,j,k)%UNTITLED3Summaryofthisfunctiongoeshere%Detailedexplanationgoesherec=[];[b,c]=xianglian(b,i,j
6、,k);ifisempty(c)~=1forg=1:length(c(:,1))[b,d]=xianglian(b,c(g,1),c(g,2),k);b=kuai(b,c(g,1),c(g,2),k);endelsereturnend%----------------------------------------------------------------------%下面是主函数部分clearclca=rand(8);b=a>0.5;b=double(b);b1=bk=2;fori=1:8forj=1:8ifb(i,j)==1b=kuai(b,i,j,k);k=k+1;ende
7、ndendfori=1:8forj=1:8ifb(i,j)~=0b(i,j)=b(i,j)-1;endendendB%提示:一定要把这三段程序放到三个m文件中才行