The following matrix a represents a from-to distance:
a = [0 3 5 6; 4 0 2 9; 9 1 0 4; 8 3 8 0];
a =
0 3 5 6
4 0 2 9
9 1 0 4
8 3 8 0
(I.e. From 2 To 4 = 9, From 1 To 2 = 3, etc.)
matrix a is static(not changing) and there is another matrix b which changes. An example input is:
b = [1; 4; 2; 1; 3; 4; 1];
b =
1
4
2
1
3
4
1
I am looking to find the distance between the first row and the second row — and perform that task for all rows to output:
b =
1
4 6
2 3
1 4
3 5
4 4
1 8
Where the second column is the value obtained from matrix a.
Here is a one line solution:
Alternatively, the non-vectorized solution is:
So which solution is optimal? On my machine (R2012b, Linux Mint v12), the tipping-point length of
bis about 650. Ifbis larger than 650, then use the vectorized solution (ie the one-liner). Ifbis smaller than 650, then use the loop.By the way, if you are wondering, the one-line solution works by converting the successive pairs in
binto row and column indices for the matrixaby using thesub2indfunction. The solution vector is then found by indexingausing these indices.ps An asymmetric distance matrix? Sounds like an interesting problem!