[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

help with slicing/replacing matrix sections.

Erik Lind

1/14/2008 7:25:00 PM

I see a more complicated thread on a similar sounding question, but my
question is simpler, I hope.

I have a large numpy matrix, initially created as:

Mat = zeros((a,b), int)

and a smaller array with other data

Sub = [1,2,3,4,5],[6,7,8,9,0]

I want to replace a section of Mat matrix with Sub matrix without having to
loop through each cell in each matrix individually.

I thought index/slice assignments, should be able to do that, but I can only
get it to work (as per book examples) with simple arrays. Every syntax
combination I have tried gives one error or another, typically "can't
broadcast an object....", but intuitively it seems there should be a simple
solution.

In short, how do I insert the data in the two (or any number of) rows in
Sub[0:2] into any part of Mat starting at Mat[x,y] without using "for" loops
?


1 Answer

Robert Kern

1/14/2008 7:39:00 PM

0

Erik Lind wrote:
> I see a more complicated thread on a similar sounding question, but my
> question is simpler, I hope.

numpy questions are usually answered better on the numpy mailing list.

http://www.scipy.org/Mai...

> I have a large numpy matrix, initially created as:
>
> Mat = zeros((a,b), int)
>
> and a smaller array with other data
>
> Sub = [1,2,3,4,5],[6,7,8,9,0]
>
> I want to replace a section of Mat matrix with Sub matrix without having to
> loop through each cell in each matrix individually.
>
> I thought index/slice assignments, should be able to do that, but I can only
> get it to work (as per book examples) with simple arrays. Every syntax
> combination I have tried gives one error or another, typically "can't
> broadcast an object....", but intuitively it seems there should be a simple
> solution.
>
> In short, how do I insert the data in the two (or any number of) rows in
> Sub[0:2] into any part of Mat starting at Mat[x,y] without using "for" loops
> ?

In [11]: Sub = array([[1,2,3,4,5],[6,7,8,9,0]])

In [12]: Mat = zeros((10, 10), int)

In [13]: Mat[5:5+2,4:4+5] = Sub

In [14]: Mat
Out[14]:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 2, 3, 4, 5, 0],
[0, 0, 0, 0, 6, 7, 8, 9, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco