Loop for concentric squares

8 views (last 30 days)
hoennnoodle
hoennnoodle on 23 Feb 2021
Edited: Adam Danz on 23 Feb 2021
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.

Accepted Answer

Adam Danz
Adam Danz on 23 Feb 2021
Edited: Adam Danz on 23 Feb 2021
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

More Answers (0)

Categories

Find more on Line Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!