Info
This question is closed. Reopen it to edit or answer.
Please help me vectorize this code
1 view (last 30 days)
Show older comments
It is a simple nested for loop, I want to learn how to vectorize such loops.
The distance function is an O(1) function with no loops within.
Basically, I have a 2D matrix of size 16x2000. I want to determine the distance between every column with every other column hence making a 2000x2000 matrix.
for i=1:nvoxels
for j=i:nvoxels
a=img(1:16,i);
b=img(1:16,j);
m(i,j)=distance(a,b);
end
end
The distance function is :
function lambda = distance(a,b)
var1=var(a);
var2=var(b);
rho=corrcoef(a,b);
rho=rho(1,2);
rho=rho^2;
lambda = (var1 + var2 - sqrt(((var1+var2)^2)-(4*var1*var2*(1-rho))))/2;
if var1==var2
lambda=0;
end
1 Comment
Jan
on 5 Nov 2015
Please note, that the required changes must appear inside the function distance, not only in the shown code. So please add the code of this function here also by editing the original question (not as a comment, please).
Answers (1)
Jan
on 5 Nov 2015
Edited: Jan
on 5 Nov 2015
At first cleanup your code for a fair comparison:
for i = 1:nvoxels
a = img(:, i);
for j = i:nvoxels
b = img(:, j);
m(j,i) = distance(a, b); % Swapped orientation
end
end
Afterwards the function distance must be vectorized - so please insert it in your question. But as usual it is not guaranteed, that the vectorized function is faster because the allocation of temporary memory might cost more time than the faster processing of the data saves.
I've swapped the orientation of m, because writing to the array columnwise is usually faster than the rowwise access.
1 Comment
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!