[Numpy-discussion] assigning to submatrix

Perry Greenfield perry at stsci.edu
Tue Jul 29 11:00:04 CDT 2003

> If I have a large matrix, say
>   a = zeros( (20,20) )
> and a small matrix
>   b = ones( 3,4 )
> and a list of row indices and a list of col indices
>   rind = [2,4,9,15]
>   cind = [1,4,12]
> what is the best way to assign the submatrix to a[rind,cind].  I
> understand this is possible in numarray, but is there a good way to do
> it in Numeric?
> In matlab, you could do a(rind, cind)=b;  Is there some reshape, put
> magic I can do to make this efficient in Numeric?
> Thanks,
> John Hunter

Note that numarray doesn't do the same thing as matlab in this
regard. In particular, the expression

a[rind, cind] = b

would fail since it is expecting an array on the right hand side
that is the same shape as the index arrays. The assignment here
is taken to mean:

a[rind[0], cind[0]] = b[0]
a[rind[1], cind[1]] = b[1]


a[rind[0], cind[0]] = b[0,0]

To do what you want doesn't currently have any atomic operation
in numarray. Is this widely used?

At the moment I think you would be forced to iterate over
one dimension. E.g.,

for i in range(len(rind)):
    a[cind, rind[i]] = b[:, i]

[Note that I reordered the index arrays to match b; I wasn't sure
what was intended]

There may be some clever way to avoid the explicit looping. Nothing
prevents the addition of such a feature to numarray (other than
work!), but it would likely have to use a function. I think
the current defintion of how multiple index puts and takes work with
brackets is more useful than the interpretation you are using and isn't
likely to change.


More information about the Numpy-discussion mailing list