views:

838

answers:

2

I've got an n-by-k sized matrix, containing k numbers per row. I want to use these k numbers as indexes into a k-dimensional matrix. Is there any compact way of doing so in MATLAB or must I use a for loop?

This is what I want to do (in MATLAB pseudo code), but in a more MATLAB-ish way:

for row=1:1:n
    finalTable(row) = kDimensionalMatrix(indexmatrix(row, 1),...
          indexmatrix(row, 2),...,indexmatrix(row, k))
end
+4  A: 

To treat the elements of the vector indexmatrix(row, :) as separate subscripts, you need the elements as a cell array. So, you could do something like this

subsCell = num2cell( indexmatrix( row, : ) );
finalTable( row ) = kDimensionalMatrix( subsCell{:} );

To expand subsCell as a comma-separated-list, unfortunately you do need the two separate lines. However, this code is independent of k.

Edric
Great! Can you get it independent of the number of rows too?
AnnaR
+5  A: 

If you want to avoid having to use a for loop, this is probably the cleanest way to do it:

indexCell = num2cell(indexmatrix,1);
linearIndexMatrix = sub2ind(size(kDimensionalMatrix),indexCell{:});
finalTable = kDimensionalMatrix(linearIndexMatrix);

EXPLANATION:

The first line puts each column of indexmatrix into separate cells of a cell array using NUM2CELL. This allows us to pass all k columns as a comma-separated list into SUB2IND, a function that converts subscripted indices (row, column, etc.) into linear indices (each matrix element is numbered from 1 to N, N being the total number of elements in the matrix). The last line uses these linear indices to replace your for loop. A good discussion about matrix indexing (subscript, linear, and logical) can be found here.

SOME MORE FOOD FOR THOUGHT...

The tendency to shy away from for loops in favor of vectorized solutions is something many MATLAB users (myself included) have become accustomed to. However, newer versions of MATLAB handle looping much more efficiently. As discussed in this answer to another SO question, using for loops can sometimes result in faster-running code than you would get with a vectorized solution.

I'm certainly NOT saying you shouldn't try to vectorize your code anymore, only that every problem is unique. Vectorizing will often be more efficient, but not always. For your problem, the execution speed of for loops versus vectorized code will probably depend on how big the values n and k are.

gnovice