Info

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

Vectorized code not faster

1 view (last 30 days)
Bart van Essen
Bart van Essen on 20 Nov 2015
Closed: MATLAB Answer Bot on 20 Aug 2021
Hello, i had the following code:
for i=1:length(rho);
for j=i:length(theta);
PolarImage(j,i)=diag(CartImage(Y(i,j),X(i,j)));
end
end
Elapsed time is 0.019816 seconds
I changed it to:
for i=1:length(rho);
PolarImage(:,i)=diag(CartImage(Y(i,:),X(i,:)));
end
Elapsed time is 0.093083 seconds
I do not understand, why the vectorized code is a lot slower than the previous one. does anyone know an efficient way, for faster calculation? thanks ahead, Bart
  3 Comments
Bart van Essen
Bart van Essen on 20 Nov 2015
CartImage is a binary Image file, so it is a binary matrix
Walter Roberson
Walter Roberson on 20 Nov 2015
What value are you expecting diag(CartImage(Y(i,j),X(i,j))) to be that is different from CartImage(Y(i,j),X(i,j)) ?

Answers (1)

Walter Roberson
Walter Roberson on 20 Nov 2015
for i = 1:length(rho)
idx = sub2ind(size(CartImage), Y(i,:), X(i,:));
PolarImage(:,i) = CartImage(idx);
end
Or to be more efficient:
nrow = size(CartImage,1);
for i = 1:length(rho)
PolarImage(:,i) = CartImage( (X(i,:) - 1) * nrow + Y(i,:) );
end
  2 Comments
Bart van Essen
Bart van Essen on 20 Nov 2015
Edited: Bart van Essen on 20 Nov 2015
i had made a mistake copying my code, it was meant to be:
for i=1:length(rho);
for j=i:length(theta);
PolarImage(j,i)=CartImage(Y(i,j),X(i,j));
end
end
so what i basically wanted to know, if you had ideas how i can vectorize the code of the double loop to make it faster, my vectorization using the diag command is 10 times slower than the double loop :/
Walter Roberson
Walter Roberson on 20 Nov 2015
nrow = size(CartImage,1);
PolarImage = CartImage( (X - 1) * nrow + Y ) .';

Community Treasure Hunt

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

Start Hunting!