3

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,

2 Answers 2

4

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.

  1. Unlike matlab where the first element of an array is array[1], in python the first element of an array is 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].

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad I could help. I wouldn't normally bug someone about this, but since you appear to be hew here, I'll point out that you should accept answers that work for you so that people don't keep coming back to your question to give an answer.
0

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::]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.