Sometimes is useful to assign arrays with one index only. In Matlab this is straightforward:
M = zeros(4);
M(1:5:end) = 1
M =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
Is there a way to do this in Numpy? First I thought to flatten the array, but that operation doesn't preserve the reference, as it makes a copy. I tried with ix_ but I couldn't manage to do it with a relatively simple syntax.
Those who are transitioning from academic research will find Python's NumPy library to be a natural transition point because of its similarity to the MATLAB programming language. Proficiency in NumPy brings the data scientist one step closer to unlocking Python's full potential for comprehensive data analytics.
MATLAB® and NumPy have a lot in common, but NumPy was created to work with Python, not to be a MATLAB clone.
Indexing can be done in numpy by using an array as an index. In case of slice, a view or shallow copy of the array is returned but in index array a copy of the original array is returned. Numpy arrays can be indexed with other arrays or any other sequence with the exception of tuples.
We can assign new values to an element of a NumPy array using the = operator, just like regular python lists. A few examples are below (note that this is all one code block, which means that the element assignments are carried forward from step to step).
You could try numpy.ndarray.flat, which represents an iterator that you can use for reading and writing into the array.
>>> M = zeros((4,4))
>>> M.flat[::5] = 1
>>> print(M)
array([[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]])
Note that in numpy the slicing syntax is [start:stop_exclusive:step], as opposed to Matlab's (start:step:stop_inclusive).
Based on sebergs comment it might be important to point out that Matlab stores matrices in column major, while numpy arrays are row major by default.
>>> M = zeros((4,4))
>>> M.flat[:4] = 1
>>> print(M)
array([[ 1., 1., 1., 1.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
To get Matlab-like indexing on the flattened array you will need to flatten the transposed array:
>>> M = zeros((4,4))
>>> M.T.flat[:4] = 1
>>> print(M)
array([[ 1., 0., 0., 0.],
[ 1., 0., 0., 0.],
[ 1., 0., 0., 0.],
[ 1., 0., 0., 0.]])
You could do this using list indices:
M = np.zeros((4,4))
M[range(4), range(4)] = 1
print M
# [[ 1. 0. 0. 0.]
# [ 0. 1. 0. 0.]
# [ 0. 0. 1. 0.]
# [ 0. 0. 0. 1.]]
In this case you could also use np.identity(4)
Another way using unravel_index
>>> M = zeros((4,4));
>>> M[unravel_index(arange(0,4*4,5),(4,4))]= 1
>>> M
array([[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With