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.
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Bo Li
2017-10-10
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]).
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Python Package Integration 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!