将此片段从Matlab移植到Python

时间:2012-10-22 13:57:41

标签: python matlab

我在Matlab中有以下代码片段,并希望将其移植到Python。

for i=1:runs;
   tic;
   datmat=importdata('data.txt',' ');
    Limits_Area=[1,261,522,784,1045,1305,1565,1827,2088,2349,2610,2871,3131,3158];
   for k=1:2000;
      for j=1:13;
         Year_Data=datmat.data(Limits_Area(j):Limits_Area(j+1)-1,4:37);
         Min_Year=min(Year_Data);
         Max_Year=max(Year_Data);
         Mean_Year=mean(Year_Data);
         GainLoss_Year=100-(Year_Data(1,:)+0.00000001)./(Year_Data(end,:)+0.00000001)*100;
     end;
   end;

我真的很难过

Year_Data=datmat.data(Limits_Area(j):Limits_Area(j+1)-1,4:37);

part ....任何指示?

谢谢

1 个答案:

答案 0 :(得分:2)

你尝试过numpy吗?它是一个科学计算库,看起来像Matlab。例如:

  

在Matlab中:   a(1:5,:)

     

在Numpy:   a[0:5] or a[:5] or a[0:5,:]

退房: Numpy for Matlab Users

如果您不想使用Numpy,请尝试理解列表:

Year_Data = [ [datmat.data(i,j) for j in range (4,38) ] for i in range(j,j+2) ]

编辑:

for i in range(runs) :
    datamat = numpy.genfromtxt('data.txt',delimiter=' ', newline ='\n' ) 
    // Adapt the previous line to the format of your txt file
    // at this point you should have a numpy.array object with the right shape
    Limits_Area= numpy.array( [1,261,522,784,1045,1305,1565,1827,2088,2349,2610,2871,3131,3158] )
    for k in range(2000):
        for j in range(13):
            Year_Data = datmat[ Limits_Area(j):Limits_Area(j+1)-1 , 4:37 ]
            etc etc ...

注意:Matlab数组索引从1变为n,而numpy数组索引从0变为n-1