How to vectorize nested for loops

2 views (last 30 days)
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.

Accepted Answer

Rik
Rik on 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 Comment
Simon Allosserie
Simon Allosserie on 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 :)

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!