numpy array creating with a sequence

后端 未结 9 1394
陌清茗
陌清茗 2020-12-15 20:34

I am on my transitional trip from MATLAB to scipy(+numpy)+matplotlib. I keep having issues when implementing some things. I want to create a simple vector array in three dif

9条回答
  •  臣服心动
    2020-12-15 20:51

    Just want to point out for any other people going from MATLAB to Numpy that you can construct an np.r_ array with colons and then use it to index

    E.g., if you have in matlab

    arr_ones = ones(10,10)
    

    Or in Numpy

    arr_ones = np.ones([10,10])
    

    You could in Matlab take only columns 1 through 5 as well as 7 like this:

    arr_ones(:,[1:5 7])
    

    Doing the same in Numpy is not (at least for me) intuitive. This will give you an "invalid syntax" error:

    arr_ones[:,[1:5,7]]
    

    However this works:

    inds = np.r[1:5,]
    arr_ones[:,inds]
    

    I know this is not technically a new answer, but using a colon to construct an array when indexing into a matrix seems so natural in Matlab, I am betting a lot of people that come to this page will want to know this. (I came here instead of asking a new question.)

提交回复
热议问题