0

I want to eliminate the for loop from the code below and vectorize it, but it is a 2 dimensional operation. Can you please help me.

for i=1:10 savingsFull(i,:) = distances(i,9)+distances(9,knnIdx(i,:))-distances(i,knnIdx(i,:)); end 

here, "distances" is a 10x10 symmetric matrix and "knnIdx" is a 10x2 matrix as below:

 1 10 2 10 3 8 4 8 5 4 6 5 7 2 8 4 9 8 10 1 

"savingsFull" is also a 10x2 matrix.

2
  • use bsxfun to vectorize Commented Jul 9, 2013 at 20:49
  • I treated all matrices as a vector and applied the formula on it. Commented Jul 10, 2013 at 7:25

1 Answer 1

1

Following code should help:

savingsFull = distances(:, [9 9]) + [distances(9, knnIdx(:, 1)).', distances(9, knnIdx(:, 2)).'] - [diag(distances(:, knnIdx(:, 1))), diag(distances(:, knnIdx(:, 2)))] 

If first column of knnIdx are consequent numbers from 1 to 10, then you can simplify to

savingsFull = distances(:, [9 9]) + [distances(9, knnIdx(:, 1)).', distances(9, knnIdx(:, 2)).'] - [diag(distances), diag(distances(:, knnIdx(:, 2)))] 
Sign up to request clarification or add additional context in comments.

3 Comments

would you please describe me what the dot operator does in distances(9, knnIdx(:, 1)).' Thanks
@remo, the difference between ' and .' operators is that .' transposes a matrix and ' only changes dimensions. So there is a simple relation between them: A' = conj(A.');. So distances(9, knnIdx(:, 1)).' leads to a column-vector instead of row-vector. So, assuming that distance is real-valued, there should be no difference between ' and .'.
Seems like I've swapped definitions in previous comment. Sorry =) Anyway you can check matlab reference for both of them. ctranspose, transpose

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.