Info

This question is closed. Reopen it to edit or answer.

Please help me vectorize this code

1 view (last 30 days)
awi
awi on 5 Nov 2015
Closed: MATLAB Answer Bot on 20 Aug 2021
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
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
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
awi
awi on 5 Nov 2015
I have added the distance code. Please check.

Community Treasure Hunt

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

Start Hunting!