Reputation: 145
I have matlab array operations as the following :
[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:
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.
can anyone tell me what is wrong?
Thanks,
Upvotes: 3
Views: 1128
Reputation: 145
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::]
Upvotes: 0
Reputation: 4928
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.
array[1]
, in python the first element of an array is array[0]
. 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]
.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.
Upvotes: 4