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 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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]?
0 Commenti
Risposte (1)
Bo Li
il 10 Ott 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]).
Vedere anche
Categorie
Scopri di più su Python Package Integration in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!