Consider a matrix M and a set of subscripts stored in columns I and J. I need to access the elements designated by I & J without converting them to linear indices (i.e. using sub2ind). E.g.
M = [1 2 3;4 5 6;7 8 9];
I = [1 1 1];
J = [1 2 3];
VALS = [1 2 3];
Also, doing the following is not feasible since I & J are huge :
VALS = diag(M(I,J));
And for demonstration, this is not what I'm looking for,
VALS = M(sub2ind(size(M),I,J));
Essentially sub2ind seems to be taking a lot of time and right now I'm looking for methods to access these elements without converting the subscripts to indices. Any other way is feasible as long as it's faster than the method using sub2ind.
This may be faster than using SUB2IND:
[r,c] = size(M); % Get the size of M
vals = M(I+r.*(J-1)); % Compute a linear index with vector operations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With