How to vectorize nested for loops

2 vues (au cours des 30 derniers jours)
Simon Allosserie
Simon Allosserie le 24 Sep 2021
I am making a matrix B that represents a halve sphere in grayscale values. This means grayscale ~ height (so 0 = black = bottom and 2^16 = white = heighest point).
The final matrix looks like this:
At the moment I do it like this
A=abs(-rowsA:rowsA); % e.g. 5 4 3 2 1 0 1 2 3 4 5
sizeA = numel(A);
B=zeros(sizeA,sizeA);
for i=1:sizeA
for j=1:sizeA
B(i,j)=(min(R-sqrt(R^2-(pix*A(i))^2-(pix*A(j))^2),ht))/ht*65535;
end
end
Now would like to vectorize this to eliminate the nested for loops. I have no idea how to handle the A(i) and A(j) parts in the fomula. Any ideas?
If anyone would like to simulate, rowsA=59, pix = 25.4/600, R = 2.5, ht = 1.5.

Réponse acceptée

Rik
Rik le 24 Sep 2021
ndgrid will do the trick:
rowsA=59; pix = 25.4/600; R = 2.5; ht = 1.5;
A=abs(-rowsA:rowsA); % e.g. 5 4 3 2 1 0 1 2 3 4 5
sizeA = numel(A);
B=zeros(sizeA,sizeA);
for i=1:sizeA
for j=1:sizeA
B(i,j)=(min(R-sqrt(R^2-(pix*A(i))^2-(pix*A(j))^2),ht))/ht*65535;
end
end
[Ai,Aj]=ndgrid(A);
B2=(min(R-sqrt(R^2-(pix*Ai).^2-(pix*Aj).^2),ht))/ht*65535;
imshow(B2,[])
isequal(B,B2)
ans = logical
1
  1 commentaire
Simon Allosserie
Simon Allosserie le 24 Sep 2021
Thanks for your swift reply, Rik!
This grid approach is a new way of thinking for me. Now I'll try to apply it myself to some similar loops I want to optimize :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by