2018-11-25 06:52

# matlab 区域计算问题，求一段 matlab 程序

80

`````` J=zeros(100);
J(50:59,30:39)=1;
J(50:59,70:79)=1;
J(50:59,50:59)=1;
J(70:79,40:49)=1;
``````
• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享
• 邀请回答

#### 1条回答

• `````` J = zeros(100);
J(50:59,30:39)=1;
J(50:59,70:79)=1;
J(50:59,50:59)=1;
J(70:79,40:49)=1;

[rows, columns] = size(J);
count = 0;

% 找到一个值为1的点的坐标
[y, x] = find(J==1, 1);
while ~isempty(y)
count = count + 1;
flag = 1;
ns = 1;
sy(1) = y;
sx(1) = x;
while flag
nns = 0;
nsy = [];
nsx = [];
% 向周围扩散
for i = 1:ns
J(sy(i), sx(i)) = 0;
% top
if sy(i) > 1 && J(sy(i)-1, sx(i))==1
nns = nns + 1;
nsy(nns) = sy(i) - 1;
nsx(nns) = sx(i);
end
% down
if sy(i) < rows && J(sy(i)+1, sx(i))==1
nns = nns + 1;
nsy(nns) = sy(i) + 1;
nsx(nns) = sx(i);
end
% left
if sx(i) > 1 && J(sy(i), sx(i)-1)==1
nns = nns + 1;
nsy(nns) = sy(i);
nsx(nns) = sx(i) - 1;
end
% right
if sx(i) < columns && J(sy(i), sx(i)+1)==1
nns = nns + 1;
nsy(nns) = sy(i);
nsx(nns) = sx(i) + 1;
end
end

ns = nns;
sy = nsy;
sx = nsx;

if ns == 0
flag = 0;
end

end

[y, x] = find(J==1, 1);
end

disp(count);
``````
点赞 评论 复制链接分享