我有一个带有一个非零条目的矩阵;
InfectionMatrix = zeros(10,10);
InfectionMatrix(5,5) = 1;
我想看看这个矩阵找到所有值为1的元素然后将周围元素的值增加0.125
for k = 1:1:8
for j = 1:1:10
for i = 1:1:10
if InfectionMatrix(i,j) == 1
InfectionMatrix(i-1,j) = InfectionMatrix(i-1,j)+ 0.125;
InfectionMatrix(i-1,j+1) = InfectionMatrix(i-1,j+1)+ 0.125;
InfectionMatrix(i-1,j-1) = InfectionMatrix(i-1,j-1)+ 0.125;
InfectionMatrix(i,j+1) = InfectionMatrix(i,j+1)+ 0.125;
InfectionMatrix(i,j-1) = InfectionMatrix(i,j-1)+ 0.125;
InfectionMatrix(i+1,j+1) = InfectionMatrix(i+1,j+1) + 0.125;
InfectionMatrix(i+1,j-1) = InfectionMatrix(i+1,j-1) + 0.125;
InfectionMatrix(i+1,j) = InfectionMatrix(i+1,j) + 0.125;
end
end
end
end
这就是我所做的,也就是我所说的周围元素。我只能想到使用一个循环这样做,但这样它可以按顺序查看元素并且不会给出一个' wave'影响。
这是一种想法;
0 0 0 0 0
0 0 1 0 0 --->
0 0 0 0 0
0 1 1 1 0
0 1 1 1 0 ---->
0 1 1 1 0
1 1 1 1 1
1 1 1 1 1 ---->
1 1 1 1 1
矩阵表示多次迭代。
最大值可以是1,所有值都从中心传播,每次增加0.125。
答案 0 :(得分:1)
试试这个
for k = 1:1:8
IMONES = (InfectionMatrix==1);
KERNEL = 0.125*ones(3,3);
KERNEL(2,2) = 0;
InfectionMatrix += conv2(IMONES,KERNEL,'same');
end
请注意,我已将“波浪效应”解释为影响两个最里面迭代中前面元素的后续元素。我以为你不希望这种情况发生。上述解决方案没有“波浪效应”
答案 1 :(得分:0)
这应该可以解决问题:
function im = spread(im)
% Retrieve the matrix data...
[im_rows,im_cols] = size(im);
im_min = min(im(im>0));
% Declare the indces...
indices = [];
for i = 1:im_rows
for j = 1:im_cols
% Skip the process if the current center is not equal to 1...
if (im(i,j) ~= im_min)
continue;
end
% Retrieve the neighboring column and row offsets...
c = bsxfun(@plus,j,[-1 0 1 -1 1 -1 0 1]);
r = bsxfun(@plus,i,[-1 -1 -1 0 0 1 1 1]);
% Filter the invalid positions...
idx = (c > 0) & (c <= im_cols) & (r > 0) & (r <= im_rows);
% Transform the valid positions into linear indices and discard the invalid ones...
idx = (((idx .* c) - 1) .* im_rows) + (idx .* r);
idx = reshape(idx.',1,numel(idx));
% Keep only the valid indices...
idx = idx(idx > 0);
idx = idx(im(idx) == 0);
indices = [indices, idx];
end
end
% Increase the non-minimum (and non-zero) values...
im(im >= im_min) = im(im >= im_min) + 0.125;
% Take the elements with a value equal to 0 and increase them...
im(indices) = im(indices) + 0.125;
end
以下是一个示例用法:
im = zeros(10,10);
im(5,5) = 0.125;
figure();
colormap(hot());
hold on;
for i = 1:8
im = spread(im);
subplot(4,2,i);
imagesc(im);
title(['Step ' num2str(i)]);
end
hold off;
caxis([0 max(max(im))]);