我知道下面的代码:
N = 5;
assert(N>1 && mod(N,2)==1);
A = zeros(N);
% diamond mask
N2 = fix(N/2);
[I,J] = meshgrid(-N2:N2);
mask = (abs(I) + abs(J)) == N2;
% fill with zeros
A(mask) = 1;
将矩阵A
转换为:
A=
0 0 1 0 0
0 1 0 1 0
1 0 0 0 1
0 1 0 1 0
0 0 1 0 0
但我希望这颗钻石充满1。 我该怎么办?
答案 0 :(得分:4)
这是使用bsxfun
-
Nh = (N+1)/2;
range_vec = [1:Nh Nh-1:-1:1];
out = bsxfun(@plus,range_vec(:),range_vec) > Nh
样品运行 -
1)N = 5:
out =
0 0 1 0 0
0 1 1 1 0
1 1 1 1 1
0 1 1 1 0
0 0 1 0 0
2)N = 9:
out =
0 0 0 0 1 0 0 0 0
0 0 0 1 1 1 0 0 0
0 0 1 1 1 1 1 0 0
0 1 1 1 1 1 1 1 0
1 1 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1 0
0 0 1 1 1 1 1 0 0
0 0 0 1 1 1 0 0 0
0 0 0 0 1 0 0 0 0
答案 1 :(得分:2)
mat = tril(ones(N), round((N-1)/2)) - tril(ones(N), round((-N-1)/2));
out = mat & flip(mat)
N
的奇数值:
% N = 5;
out =
0 0 1 0 0
0 1 1 1 0
1 1 1 1 1
0 1 1 1 0
0 0 1 0 0
甚至是N
的值:
% N = 4;
out =
0 1 1 0
1 1 1 1
1 1 1 1
0 1 1 0
答案 2 :(得分:1)
您需要的是根据每个阵列位置的Manhattan distance将1或0返回到钻石的中心
N = 5;
assert(N>1 && mod(N,2)==1);
A = false(N);
[m, n] = size(A); %dimensions of A
X = floor([m, n]/2); %floored division gives integer indices of center of array
x = X(1); y = X(2);
radius = m/2; %half the height gives the radius
for a = 1 : m
for b = 1 : n
A(a,b) = abs(a-x)+abs(b-y) <= radius; %test if manhatten distance <= radius
end
end
这自然需要编辑以适合您的特定情况......特别是,通过修改x, y
,您的钻石中心可以实际放置在任何位置,并且半径可以小于或大于宽度的一半如果您愿意,可以选择数组。
答案 3 :(得分:0)
只需添加for loop
并填充所有对角线:
N = 5;
assert(N>1 && mod(N,2)==1);
A = zeros(N);
% diamond mask
N2 = fix(N/2);
[I,J] = meshgrid(-N2:N2);
for id = 0:N2
A((abs(I) + abs(J)) == id) = 1;
end