To work with a Python® variable in MATLAB®, convert the Python object to a MATLAB array, and then index into the array as needed. You also can preserve the Python object without converting, for example, to pass the object to a Python method.
A Python
container is typically a sequence type
(list or tuple) or a mapping
type (dict). In Python, use square brackets [] or the
operator.getitem function to access an element in the container. Scalar
string arguments can be used to index into the container.
Python sequence types behave like MATLAB cell arrays.
Get a subsequence using smooth-parenthesis () indexing.
li = py.list({1,2,3,4});
res = li(2:3)res =
Python list with no properties.
[2.0, 3.0]Use curly braces {} to get the contents of the element.
res = li{1}res =
1For mapping types, use curly braces with the Python key argument.
patient = py.dict(pyargs('name','John Doe','billing',127)); patient{"billing"}
ans = 127
MATLAB displays information for your system.
p = py.sys.path; class(p)
ans = py.list
Index into p.
p(1)
p{1}ans =
Python list with no properties.
['c:\\work']
ans =
Python str with no properties.
c:\workInspect dimensions.
len = length(p) sz = size(p)
len =
11
sz =
1 11MATLAB converts a sequence type into a 1-by-N
array.
Python uses zero-based indexing; MATLAB uses one-based indexing. When you call a Python function, such as py.sys.path, the index value of the first
element of a Python container, x, is int32(0). The index
value for the last element is int32(py.len(x)-1).
You can access data in Python container objects, like lists and dictionaries, with index values, similar to referencing an element in a MATLAB matrix. There are, however, ways to index into matrices which are not supported for these Python types.
| Indexing Features Not Supported in MATLAB |
|---|
Use of square brackets, |
Indexing into a container type that does not inherit from
|
Logical indexing. |
Accessing data in a container with an arbitrary array of indices. An
index must be of the form |
Comma-separated lists. |
|