Index higher dimensions in MATLAB Engine API for Python

1 次查看(过去 30 天)
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 个评论
Adam Wasserman
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
Paul 2020-8-11
Thanks for the tip. I guess I still see the issue as I stated it above, being "a limitation of the nested list format of the numeric matlab-python objects." In other words, if Matlab arrays were treated as numpy arrays, then everything could be sliced along any dimension. But I imagine that Mathworks wanted to make sure their API didn't require anything outside of the Python Standard Library, so they treat them as lists.
Python's list comprehension makes it easy enough to deal with, but I was hoping there might be some Matlab function that does the same thing as numpy.take(), which would let me slice the Matlab array directly with the Matlab engine. I suppose I could write my own Matlab function that simply takes an array and some indices as the input, then subsets the array by those indices and returns that. There is a chance that could be a bit faster than list comprehension, in which case, I will report back here with the results.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Call MATLAB from Python 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by