Reputation: 13206
I have an x dimensional matrix in Numpy. For this example, I will use a 2x2 array.
np.array([[2, 2], [3,3]])
How would I alternate adding a row and column of some value so the result would look like:
array([[2, x, 3, x],
[x, x, x, x].
[2, x, 3, x],
[x, x, x, x]])
This answer gives a helpful start by saying to set rows in a correctly-sized destination matrix b
from a matrix a
like so a[::2] = b
but what does the ::2
do in the slicing syntax and how can I make it work on columns?
In short what do the x
y
and z
parameters do in the following: a[x:y:z]
?
Upvotes: 0
Views: 141
Reputation: 1055
If I understand what you want correctly, this should work:
import numpy as np
a = np.array([[2,2],[3,3]])
b = np.zeros((len(a)*2,len(a)*2))
b[::2,::2]=a
This 'inserts' the values from your array (here called a
) into every 2nd row and every 2nd column
Edit: based on your recent edits, I hope this addition will help:
x:y:z
means you start from element x
and go all the way to y
(not including y
itself) using z
as a stride (e.g. 2
, so every 2 elements, so x
, x+2
, x+4
etc up to x+2n
that is the closest to y
possible)
so ::z
would mean ALL elements with stride z
(or ::2
for every 2nd element, starting from 0
)
You do that for each 'dimension' of your array, so for 2d you'd have [::z1,::z2]
for going through your entire data, striding z1
on the rows and z2
on the columns.
If that is still unclear, please specify what is not clear in a comment.
One final clarification - when you type only :
you implicitly tell python 0:len(array)
and the same holds for ::z
which implies 0:len(array):z
.
and if you just type ::
it appears to imply the same as :
(though I haven't delved deep into this specific example)
Upvotes: 1