Loop for concentric squares
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Adam Danz
il 23 Feb 2021
Modificato: Adam Danz
il 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
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Line Plots in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!