Array operations/ slicing in python from matlab
matlab, multidimensional-array, python, slice
Solution
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.
- Unlike matlab where the first element of an array is `array[1]`, in python the first element of an array is `array[0]`.
- 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.
Problem
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,