Index higher dimensions in MATLAB Engine API for Python
이전 댓글 표시
Using the MATLAB Engine API in Python, I am only able to index the first dimension of a two- or more-dimensional MATLAB array. Is there any way to index a higher dimension?
import matlab.engine
import numpy as np
arr = matlab.int32([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
Here, arr is a small (4x3) sample array, though in practice I, have much larger arrays of more than two dimensions. Now if I want to take just the third column, I must first convert it to a numpy array, as in the following:
subset = np.array(arr)[:,2]
print(subset)
This returns [3, 6, 9, 12], which is what I want. But when I have much larger arrays, converting the entire MATLAB array to a numpy array is very slow, and all I want is a small slice of it. Is there any way to do this using the MATLAB API for Python? As it is now, I can subset one or more rows, but I cannot subset columns.
댓글 수: 6
Mohammad Sami
2020년 3월 10일
you can just do arr[2][:]
https://www.mathworks.com/help/matlab/matlab_external/matlab-arrays-as-python-variables.html
Paul
2020년 3월 10일
Mohammad Sami
2020년 3월 12일
What about arr[:][2]
Adam Wasserman
2020년 8월 8일
편집: Adam Wasserman
2020년 8월 8일
Unfortunately, this is actually an issue of Python lists, not MATLAB arrays. MATLAB arrays are treated as lists in Python, not numpy arrays. That means that a 2D "array" is actually a list of lists, a 3D "array" a list of lists of lists, and so on. Thus, slicing will not work in the way you'd expect for a numpy array.
There may be some workarounds, but I'm not super familiar with working with multidimensional lists. This may help: http://ilan.schnell-web.net/prog/slicing/
Paul
2020년 8월 11일
답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Call MATLAB from Python에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!