Loop for concentric squares

조회 수: 8 (최근 30일)
hoennnoodle
hoennnoodle 2021년 2월 23일
편집: Adam Danz 2021년 2월 23일
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