1

I have a matrix

 m = np.zeros((5,5))

and what to have a view on the last row

row = m[-1]

however if I add a column to m:

m = np.c_[m[:,:2],[0,0,1,1,1],m[:,2:]]

and print out row I don't get the new column.

Is there any way to get the change without use the line

row = m[-1]

again?

7
  • You want to modify your previous array in an in-place manner and that's not possible. Every time you change your array you'll end up creating a new object. Commented Aug 20, 2017 at 7:10
  • The question should be: "Why do you need to do that?" it makes no sense to me Commented Aug 20, 2017 at 7:35
  • I think maybe the problem lies in the method np.c_, which is different from ordinary operation on view of Numpy array, which can achieve in-place modification. Commented Aug 20, 2017 at 7:46
  • @ManelFornos I have a simplex tableau in m and would like to get the objective row (last row) sometimes I need to add columns to the matrix. Commented Aug 20, 2017 at 7:47
  • you want to get last row without running this row = m[-1] each time? Commented Aug 20, 2017 at 7:55

1 Answer 1

1

What you want to achieve here isn't currently possible within the bounds of the numpy library. See this answer on numpy arrays occupying a contiguous block of memory.

You can use the rx library to get around this by making a subject of the last row.

import numpy as np
from rx import Observable, Observer
from rx.subjects import Subject

m = np.zeros((5,5))

m_stream = Subject()
last_row_stream = Subject()
last_row = None

def update_last(v):
    global last_row
    last_row = v

last_row_stream.subscribe(on_next=update_last)
last_row_stream.on_next(m[-1])

print(last_row)

m_stream.map(
    lambda v: np.insert(v, 2, [0, 0, 1, 1, 1], axis=1)
).subscribe(lambda v: last_row_stream.on_next(v[-1]))

m_stream.on_next(m)


print(last_row)
Sign up to request clarification or add additional context in comments.

2 Comments

I thought of an observer pattern as well. I would like to observe on every change made so whenever m changed I would like to have row changed. Doesn't matter whether it really changed row or not. Therefore I would like to not change the insert or c_ row. Would like to have a subscribe to all changes of m.
m_stream is an observable of m. Any operations you want to carry out on m can be mapped on m_stream for a start. You can also dispose of observer(s) whenever you deem it fit. ...subscribe(lambda v: last_row_stream.on_next(v[-1])) sets a observer on m_stream that updates last_row_stream. You can dispose of this and set your very own observer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.