Assigning to columns in NumPy?

后端 未结 2 1727
情深已故
情深已故 2020-12-09 01:31

How could the following MATLAB code be written using NumPy?

A = zeros(5, 100);
x = ones(5,1);
A(:,1) = x;

Assigning to rows seems to work e

相关标签:
2条回答
  • 2020-12-09 02:18
    >>> A = np.zeros((5,100))
    >>> x = np.ones((5,1))
    >>> A[:,:1] = x
    
    0 讨论(0)
  • 2020-12-09 02:21

    Use a[:,1] = x[:,0]. You need x[:,0] to select the column of x as a single numpy array. If you have the choice of how to format x, it's better to not make it a 2-dimensional array in the first place, but just a regular (row) array:

    >>> a
    array([[ 0.,  0.,  0.],
           [ 0.,  0.,  0.],
           [ 0.,  0.,  0.],
           [ 0.,  0.,  0.],
           [ 0.,  0.,  0.]])
    >>> x = numpy.ones(5)
    >>> x
    array([ 1.,  1.,  1.,  1.,  1.])
    >>> a[:,1] = x
    >>> a
    array([[ 0.,  1.,  0.],
           [ 0.,  1.,  0.],
           [ 0.,  1.,  0.],
           [ 0.,  1.,  0.],
           [ 0.,  1.,  0.]])
    
    0 讨论(0)
提交回复
热议问题