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.

8 visualizaciones (últimos 30 días)
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[0] = A[0][::-1]
L[0] = L[0][::-1]
print(A)
[[2,2],[3,4],[5,6]]
print(L)
[[2, 1], [3, 4], [5, 6]]
Since the result of 'print(A[0][::-1])' is '[2,1]'. I just confused on why would A[0] become [2,2]?

Respuestas (1)

Bo Li
Bo Li el 10 de Oct. de 2017
This is indeed confusing. The change is made in place, that's why A[0] 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[0][::-1]" has two numbers (2, 1) and their indices are 3 and 0. "A[0]" has two elements (1, 2) and their indices are 0 and 3. What "A[0]=A[0][::-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 comentario
Lewis Liu
Lewis Liu el 12 de Oct. de 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[0]=A[0][::-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.

Iniciar sesión para comentar.

Categorías

Más información sobre Python Package Integration en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by