How to vectorize nested for loops

조회 수: 1 (최근 30일)
Simon Allosserie
Simon Allosserie 2021년 9월 24일
댓글: Simon Allosserie 2021년 9월 24일
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.

채택된 답변

Rik
Rik 2021년 9월 24일
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
Simon Allosserie
Simon Allosserie 2021년 9월 24일
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 :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by