Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing values using subscripts without using sub2ind

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.

like image 662
Jacob Avatar asked Jul 18 '09 04:07

Jacob


1 Answers

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
like image 173
gnovice Avatar answered Nov 16 '22 23:11

gnovice