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!