Loop for concentric squares

2 次查看(过去 30 天)
I want to try and make a loop that makes concentric square matricies. Just as an example, I have my sample code here:
A = zeros(20)
%difference = 2
A(3:18,3:18) = 1
A(5:16,5:16) = 0
A(7:14, 7:14) = 1
A(9:12, 8:12) = 0
So I start with a matrix of height H and there's a height difference 'difference' between each matrix (in my example, it's 2). I'm not sure how I could use a 'for' loop to automatically do this since I'm not sure how to assign a name to each subsequent matrix in my code. Any help is appreciated.

采纳的回答

Adam Danz
Adam Danz 2021-2-23
编辑:Adam Danz 2021-2-23
Vectorized version,
sz = 20; % matrix size, square, positive integer
difference = 2; % width of bands, positive integer 1 <= x <= (sz/2)-1
% Create matrix
nestedMat = (sz-difference*2):-difference*2:0;
layers = arrayfun(@(m){padarray(ones(m),(sz-m)*[.5,.5])},nestedMat);
A = mod(sum(cat(3,layers{:}),3),2);
% Plot it
imagesc(A)
axis equal
Loop version,
sz = 20; % matrix size, square, positive integer
difference = 2; % width of bands, positive integer 1 <= x <= (sz/2)-1
% Create matrix
nestedMat = (sz-difference*2):-difference*2:0;
layers = zeros(sz);
for i = 1:numel(nestedMat)
layers = layers + padarray(ones(nestedMat(i)), (sz-nestedMat(i))*[.5,.5]);
end
A = mod(layers,2);
% Plot it
imagesc(A)
axis equal

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by