How to vectorize nested for loops
2 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!