help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Indexing confusion


From: Bill Denney
Subject: Re: Indexing confusion
Date: Fri, 02 May 2008 12:38:01 -0400
User-agent: Thunderbird 2.0.0.14 (Windows/20080421)

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


reply via email to

[Prev in Thread] Current Thread [Next in Thread]