I’m wondering, what is faster for addressing a single Element of a vector:
1) direct access via
result = a(index)
or
2) access an element via a matrix multiplication e.g
a = [1 2 3 4]';
b = [0 0 1 0];
result = b*a; % Would return 3
In my oppinion (which comes from “classic” programming like C++) the first method must be more performant, because of the direct access…the second method would need a iteration through both vectors(?).
The reason why I’m asking is, that matlab is very performant on matrix and vector operations, maybe I am missing any aspect and the second method is more effective…
A quick test:
Elapsed time: 0.006 seconds
Change
a(3)tob*aElapsed time: 0.9 seconds
The performance difference is quite obvious(, and you should have done that yourself before asking this question).
Reason behind that:
No matter how efficient MATLAB’s calculation is, MATLAB still needs to fetch the number 1 by 1, and do multiplication 1 by 1, and sum up. There is no hope to be faster than a single access.
In your special case, there are all 0’s except 1, but it is useless to do optimization for single special case in my opinion, and the best optimization I can come up with still needs to access all the elements for at least once each.
EDIT:
It seems I am in quite good mood today….
Change
a(3)toa(1)*b(1)+a(2)*b(2)+a(3)*b(3)+a(4)*b(4)Elapsed time: 0.02 seconds
It seems that boundary checking (and/or other errands) take more time than the access and calculation.