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?
asked Aug 20, 2017 at 6:36
Wikunia
1,6021 gold badge18 silver badges38 bronze badges
1 Answer 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)
answered Aug 20, 2017 at 8:14
Oluwafemi Sule
39.4k1 gold badge63 silver badges88 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Wikunia
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.Oluwafemi Sule
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.lang-py
np.c_, which is different from ordinary operation on view of Numpy array, which can achieve in-place modification.row = m[-1]each time?