简体   繁体   English

来自Matlab的python中的数组运算/切片

[英]Array operations/ slicing in python from matlab

I have matlab array operations as the following : 我有如下的matlab数组操作:

[M,N]=size(I) ;
J = zeros(2*M,2*N) ;

J(1:2:end,1:2:end) = I ;

J(2:2:end-1,2:2:end-1) = 0.25*I(1:end-1,1:end-1) + 0.25*I(2:end,1:end-1) + 0.25*I(1:end-1,2:end) + 0.25*I(2:end,2:end) ;

J(2:2:end-1,1:2:end) = 0.5*I(1:end-1,:) + 0.5*I(2:end,:) ;
J(1:2:end,2:2:end-1) = 0.5*I(:,1:end-1) + 0.5*I(:,2:end) ;

I am trying to rewrite the same operations in python and I have come up with the following: 我试图用python重写相同的操作,并且提出了以下内容:

J=numpy.zeros((2*M,2*N))

J[::2,::2] = I ;

J[2:-1:2,2:-1:2] = 0.25*I[1::-1,1::-1] + 0.25*I[2::,1::-1] + 0.25*I[1::-1,2::] + 0.25*I[2::,2::] 

J[2:-1:2,1::2] = 0.5*I[1::-1,] + 0.5*I[2::,]

J[::2,2:-1:2] = 0.5*I[:,1::-1] + 0.5*I[:,2::]

however the python code gives me different results. 但是python代码给了我不同的结果。

can anyone tell me what is wrong? 谁能告诉我这是怎么回事?

Thanks, 谢谢,

Going through this piece by piece shows that you have some errors in your ranges. 逐段检查表明您的范围存在一些错误。 I think that you have misunderstood a few things about arrays in python. 我认为您误解了有关python数组的一些知识。

  1. Unlike matlab where the first element of an array is array[1] , in python the first element of an array is array[0] . 与matlab中数组的第一个元素是array[1] ,在python中,数组的第一个元素是array[0]
  2. Array slicing syntax is array[start:stop:step] , so to get every second element starting at the fifth element in the array to the end you would do array[4::2] . 数组切片的语法是array[start:stop:step] ,因此,要使第二个元素从数组的第五个元素开始到结尾,可以执行array[4::2]

Just go through this piece by piece and you will find problems. 只是一步一步地学习,您会发现问题。 For example, the first element on the right hand side of the second equation should be: 例如,第二个等式右侧的第一个元素应为:

0.25*I[0:-1, 0:-1]

Note that you don't need the second colon here since your step is 1 and in cases where you want to change the step, the step goes last. 请注意,由于您的step为1,因此此处不需要第二个冒号,并且在要更改步骤的情况下,步骤将最后执行。

so here is the correct ported code: 所以这是正确的移植代码:

J[::2,::2] = I ;

J[1:-1:2,2:-1:2] = 0.25*I[0:-1,0:-1] + 0.25*I[1::,0:-1] + 0.25*I[0:-1,1::] + 0.25*I[1::,1::] 

J[1:-1:2,0::2] = 0.5*I[0:-1,] + 0.5*I[1::,]

J[0::2,1:-1:2] = 0.5*I[:,0:-1] + 0.5*I[:,1::]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM