numpy等效的matlab矩阵码

时间:2014-12-11 22:46:11

标签: python matlab numpy

我在Matlab上有下一个代码:

cols = 7;
rows = 8;

redGrd = [0 0 0 0 0 1; 1 1 1 1 0 1; 0 0 0 0 0 1; 1 0 1 1 0 1];

redGrd(:,1)=-9999;
redGrd(1,:)=-9999;
redGrd(:,cols)=-9999;
redGrd(rows,:)=-9999

这是matlab的结果:

-9999  -9999  -9999  -9999  -9999  -9999  -9999
-9999      1      1      1      0      1  -9999
-9999      0      0      0      0      1  -9999
-9999      0      1      1      0      1  -9999
0      0      0      0      0      0      0
0      0      0      0      0      0      0
0      0      0      0      0      0      0
-9999  -9999  -9999  -9999  -9999  -9999  -9999

我想在使用numpy的python上做同样的事情然后我这样做:

import numpy as np

cols = 7
rows = 8

redGrd = np.array([[0,0,0,0,0,1],[1,1,1,1,0,1],[0,0,0,0,0,1],[1,0,1,1,0,1]])

redGrd[:,0] = -9999
redGrd[0,:] = -9999
redGrd[:,cols] = -9999 
redGrd[rows,:] = -9999 

但最后两个命令不起作用。

3 个答案:

答案 0 :(得分:3)

  1. 第一行(redGrd[:,cols] = -9999)不起作用,因为python使用zero-based indexing,而Matlab从1开始计数。所以numpy n维数组中的最后一列号码为cols-1,或仅为-1(速记)。

    如果你来自Matlab,一个非常有用的资源是NumPy for Matlab Users。它列出了很多陷阱,比如这个陷阱。

  2. 现在,第二行(redGrd[rows,:] = -9999)将失败,因为numpy不会尝试自动增加数组的大小,而Matlab会这样做。

    从程序员的角度来看,前者更有意义,因为它可以防止你意外更换数组。

    如果你想"增加"数组的大小,您必须显式

    redGrd = np.vstack((redGrd, np.zeros(rows - redGrd.shape[0], redGrd.shape[1])))
    

答案 1 :(得分:1)

初始化时,您将定义一个4x6矩阵:

redGrd = np.array([[0,0,0,0,0,1],[1,1,1,1,0,1],[0,0,0,0,0,1],[1,0,1,1,0,1]])

当您只有4行时,您无法访问第7行。您应该首先创建一个行x col矩阵,然后根据需要填充值。您可以像这样创建数组:

redGrd = np.zeros((rows, cols)) 

另外,请注意在python中你的索引是0,所以你应该使用cols -1而不是cols和行-1而不是行

答案 2 :(得分:1)

import numpy as np
cols, rows = 7, 8

redGrd = np.mat('0 0 0 0 0 1; 1 1 1 1 0 1; 0 0 0 0 0 1; 1 0 1 1 0 1')

# pad `redGrd[1:, 1:]` with -9999 on the top, left and right
redGrd = np.pad(redGrd[1:, 1:], ((1,0),(1,1)), mode='constant', constant_values=-9999)

# expand `redGrd` to the desired shape
redGrd.resize((rows, cols))    

# fill the last row with -9999
redGrd[rows-1, :] = -9999

print(redGrd)

产量

[[-9999 -9999 -9999 -9999 -9999 -9999 -9999]
 [-9999     1     1     1     0     1 -9999]
 [-9999     0     0     0     0     1 -9999]
 [-9999     0     1     1     0     1 -9999]
 [    0     0     0     0     0     0     0]
 [    0     0     0     0     0     0     0]
 [    0     0     0     0     0     0     0]
 [-9999 -9999 -9999 -9999 -9999 -9999 -9999]]
相关问题