# [Numpy-discussion] matrix indexing question

Colin J. Williams cjw@sympatico...
Mon Mar 26 06:53:09 CDT 2007

```Alan G Isaac wrote:
>>> On 3/26/07, Alan G Isaac <aisaac@american.edu> wrote:
>>>> finds itself in basic conflict with the idea that
>>>> I ought to be able to iterate over the objects in an
>>>> iterable container.  I mean really, does this not "feel"
>>>> wrong? ::
>     >>> for item in x: print item.__repr__()
>     >>> ...
>     >>> matrix([[1, 2]])
>     >>> matrix([[3, 4]])
>
>
> On Mon, 26 Mar 2007, Bill Baxter apparently wrote:
>> So you're saying this is what you'd find more pythonic?
>>>>> X[1]
>> matrix([2,3])
>>>>> X[:,1]
>> matrix([[3,
>>             4]])
>> Just trying to make it clear what you're proposing.
>
>
> No; that is not possible, since a matrix is inherently 2d.
> I just want to get the constituent arrays when I iterate
> over the matrix object or use regular Python indexing, but
> a matrix when I use matrix/array indexing.  That is ::
>
>     >>> X[1]
>     array([2,3])
>     >>> X[1,:]
>     matrix([[3, 4]])
>
> That behavior seems completely natural and unsurprising.

Perhaps things would be clearer if we thought of the constituent groups
of data in a matrix as being themselves matrices.

X[1] could represent the second row of a matrix. A row of a matrix is a
row vector, a special case of a matrix.  To get an array, I suggest that
an explicit conversion X[1].A is a clearer way to handle things.

Similarly, X[2, 3] is best returned as a value which is of a Python type.

Colin W.
>
>
>> Probably about half the bugs I get from mixing and matching matrix and
>> array are things like
>>    row = A[i]
>>    ...
>>    z = row[2]
>> Which works for an array but not for a matrix.
>
>
> Exactly!
> That is the evidence of a "bad surprise" in the current
> behavior.  Iterating over a Python iterable should provide