help with slicing/replacing matrix sections.

E

Erik Lind

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
?
 
R

Robert Kern

Erik said:
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/Mailing_Lists
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,781
Messages
2,569,615
Members
45,294
Latest member
LandonPigo

Latest Threads

Top