How to vectorize nested for loops

2 visualizzazioni (ultimi 30 giorni)
Simon Allosserie
Simon Allosserie il 24 Set 2021
Commentato: Simon Allosserie il 24 Set 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.

Risposta accettata

Rik
Rik il 24 Set 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 Commento
Simon Allosserie
Simon Allosserie il 24 Set 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 :)

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices 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!

Translated by