Loop for concentric squares
1 回表示 (過去 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.
0 件のコメント
採用された回答
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Line Plots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!