2
votes

Imagine the following matrix is defined in MATLAB:

>> matrix=10:18

matrix =

     10    11    12    13    14    15    16    17    18

Now I want to use another matrix to index the first one

>> index=[1,2;3,4]

index =

     1     2
     3     4

>> matrix(index)

ans =

     10     11
     12     13

So far so good, the size of the answer matches that of the matrix 'index'. If I use a row vector as the indexing matrix, the output is a row vector too. But the problem appears when I use a column vector as the indexing matrix:

>> index=(1:3)'

index =

     1
     2
     3

>> matrix(index)

ans =

    10    11    12

As you can see, here the size of the answer does not agree with the size of the matrix 'index'. This inconsistency in the sizes of the indexing matrix and the ans matrix prevents me from writing a piece of code accepting an indexing matrix of an arbitrary size.

I wonder if someone else has come across this problem before and has found some sort of solution to it; in other words, how can I force MATLAB to give me an ans matrix of the same size as the arbitrarily sized indexing matrix?

Cheers


Solution

@Dev-iL has nicely explained here why this is the way Matlab behaves, and @Dan has presented a general solution here. However, there was a simpler ad-hoc workaround for my code which I've explained here.

3
A workaround would be to use size. i.e. x = size(index); if x(1) > x(2), matrix(index).'; I don't know of a good solution though - Trogdor

3 Answers

4
votes

The reason comes from the function subsref.m, which is called when using parentheses:

%SUBSREF Subscripted reference.
%   A(I) is an array formed from the elements of A specified by the
%   subscript vector I.  The resulting array is the same size as I except
%   for the special case where A and I are both vectors.  In this case,
%   A(I) has the same number of elements as I but has the orientation of A.

As you can see, in the special case of vectors, the shape of the result will be the same as that of matrix in your example.

As for a workaround, IMHO Dan has the cleanest solution.

3
votes

Preallocate the output matrix with the size of index matrix. Then assign corresponding indices the corresponding values

out = zeros(size(index));
out(index) = matrix(index);

Example

index  = (1:3)'

 index =

      1
      2
      3

 >> out = zeros(size(index))

 out =

      0
      0
      0

 >> in = magic(3)

 in =

      8     1     6
      3     5     7
      4     9     2

 >> out(index) = in(index)

 out =

      8
      3
      4

 >> 
3
votes

Dev-iL has explained why it is like that. Here is a potential workaround:

reshape(matrix(index),size(index))