0

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

4
  • 2
    Understanding slice notation gives a good explanation of what the parameters x,y,z in your example do. In short, z is a "step" parameter Commented Feb 10, 2019 at 5:12
  • Just as with range and arange, and list slicing, the parameters are start, stop, step. ::2 is slice(None,None,2), means every other one. Try this: np.arange(0,4,2) Commented Feb 10, 2019 at 5:16
  • @Startec: No. Rather than shooting in the dark, you should read the above link and do some experiments with small sample arrays (generated by arange or random). Commented Feb 10, 2019 at 5:31
  • 1::2 still gives every other one, starting with 1, i.e. all odds. Row and column indexing are separated by a comma. Commented Feb 10, 2019 at 6:24

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

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.