# I am confused on 'Slicing MATLAB arrays behaves differently from slicing a Python list. Slicing a MATLAB array returns a view instead of a shallow copy.', when I learned how to use Matlab.engine in python.

64 views (last 30 days)
Lewis Liu on 6 Oct 2017
Commented: Lewis Liu on 12 Oct 2017
The sentence above is from https://www.mathworks.com/help/matlab/matlab_external/matlab-arrays-as-python-variables.html.
And there is an example like this:
Slicing MATLAB arrays behaves differently from slicing a Python list. Slicing a MATLAB array returns a view instead of a shallow copy.
Given a MATLAB array and a Python list with the same values, assigning a slice results in different results as shown by the following code.
A = matlab.int32([[1,2],[3,4],[5,6]])
L = [[1,2],[3,4],[5,6]]
A = A[::-1]
L = L[::-1]
print(A)
[[2,2],[3,4],[5,6]]
print(L)
[[2, 1], [3, 4], [5, 6]]
Since the result of 'print(A[::-1])' is '[2,1]'. I just confused on why would A become [2,2]?

Bo Li on 10 Oct 2017
This is indeed confusing. The change is made in place, that's why A becomes [2,2]. To elaborate the behavior, here is how A looks like as stored in column major:
1 3 5 2 4 6
"A[::-1]" has two numbers (2, 1) and their indices are 3 and 0. "A" has two elements (1, 2) and their indices are 0 and 3. What "A=A[::-1]" does is replacing the 1 (index 0) with 2 (index 3), which changes A to following:
2 3 5 2 4 6
And next step is replacing the 2 (index 3) with 1 (index 0), however, 1 is already replaced by 1 in previous step, so A doesn't change after this:
2 3 5 2 4 6
When printed out, it is ([2,2],[3,4],[5,6]).

#### 1 Comment

Lewis Liu on 12 Oct 2017
Thanks, inspired by your kind help, I may have known how it works:
Slicing MATLAB arrays will replace the original value step by step, and this kind of operation will result in a symmetrical vector, like this:
Provided A = matlab.int8([[1,3,5,2,4,6],[1,3,5,2,4,6]]), and set A=A[::-1], as a result A equals [[6,4,2,2,4,6],[1,3,5,2,4,6]].
However, the result '2 3 4 2 4 6' in your answer looks a bit weird.