Indexing confusion
Bill Denney
bill at denney.ws
Fri May 2 11:38:01 CDT 2008
John W. Eaton wrote:
> On 1-May-2008, Michael Grossbach wrote:
>
> | Assume a matrix
> | X = [1, 2; 3, 4];
> | To produce, say, the second element of the first row one would issue
> | X(1,2)
> | ans = 2
> | To obtain all combinations of elements in X I then use
> | fullfact(size(X))
> | ans =
> | 1 1
> | 1 2
> | 2 1
> | 2 2
> |
> | To my confusion,
> | X(fullfact(size(X)))
> |
> | produces
> | ans =
> | 1 1
> | 1 3
> | 3 1
> | 3 3
> |
> | instead of the expected
> | ans =
> | 1
> | 2
> | 3
> | 4
> | Is this intended behaviour and am I missing something?
>
> It's expected. Indexing a matrix with another single matrix produces
> a result the same size as the index. Elements of the matrix and index
> are accessed in column-major order. Note the difference between
> X(1,2) and X([1,2]). To get the result you want, try
>
> subs = fullfact (size (X));
> X(sub2ind (size (X), subs(:,1), subs(:,2)))
>
An alternative that I find more readable is:
subs = fullfact (size (X));
X(subs(:,1), subs(:,2))
I'm not positive that works (haven't tested it), but I think it does,
and to me it is more readable.
Thanks,
Bill
More information about the Help-octave
mailing list