Main Content
This example shows how to use Python® str variables in MATLAB®.
Call Python Function With str Input Arguments
To call a Python function that takes a str input argument, pass a MATLAB string or a character vector. MATLAB automatically converts the values to the Python str type.
For example, the Python os.listdir function gets information about the contents of a folder, specified as type str. Create a character vector representing a valid folder and call os.listdir. The number of example folders is based on your installed product.
folder = fullfile(matlabroot,'help','examples'); F = py.os.listdir(folder); exFolders = py.len(F)
exFolders = Python int with properties: denominator: [1×1 py.int] imag: [1×1 py.int] numerator: [1×1 py.int] real: [1×1 py.int] 267
Use Python str Type in MATLAB
In MATLAB, a Python string is a py.str variable. To use this variable in MATLAB, call char. For example, the Python os.path.pathsep function returns the Python path separator character, a semicolon (;).
p = Python str with no properties. ;
To insert this character between path names, type:
['mypath' char(p) 'nextpath']
Read Elements in Python String
You can index into a Python string the same way you index into a MATLAB string. Create a MATLAB character vector and display a range of characters.
str = 'myfile'; str(2:end)
Convert the character vector to a Python str type and display the same characters.
pstr = py.str(str); pstr(2:end)
ans = Python str with no properties. yfile
Pass MATLAB Backslash Control Character
To pass the backslash control character (\) as a Python str type, insert the new line control character \n by calling the MATLAB sprintf function. Python replaces \n with a new line.
py.str(sprintf('The rain\nin Spain.'))
ans = Python str with no properties. The rain in Spain.
Without the sprintf function, both MATLAB and Python interpret \ as a literal backslash.
py.str('The rain\nin Spain.')
ans = Python str with no properties. The rain\nin Spain.
Pass this string to the Python string method split. Python treats the MATLAB character vector as a raw string and adds a \ character to preserve the original backslash.
split(py.str('The rain\nin Spain.'))
ans = Python list with no properties. ['The', 'rain\\nin', 'Spain.']
Hi, This might be something really simple to someone who have done this, but i am struggling passing a string variable to matlab script from Python using the matlab Python API. I am doing this in 2017b
Here is what i have: 1. Matlab function: config = parseInputs(filename) %filename is a char array in matlab like "config.csv"
2. Python script file which attempts to call the above matlab function. I have saved my function parseInputs.m in the same directory as the python script.
Below is my python script:
import matlab.engine
eng = matlab.engine.start_matlab()
filename = "config.csv"
parameterMy = eng.parseInputs(filename, nargout=2)
I am getting an error like below:
File "C:\ProgramData\Anaconda3\lib\site-packages\matlab\engine\fevalfuture.py", line 82, in result
self._result = pythonengine.getFEvalResult(self._future,self._nargout, None, out=self._out, err=self._err)
MatlabExecutionError: Undefined function 'parseInputs' for input arguments of type 'char'.
Any hint on how to make it work? Thanks!
When calling a Python® function, MATLAB® converts MATLAB data into types that best represent the data to the Python language.
Pass Scalar Values to Python
double (real) | float | Use Python Numeric Variables in MATLAB |
double (complex) | complex | z = complex(1,2); py.cmath.polar(z) ans = Python tuple with no properties. (2.23606797749979, 1.1071487177940904) |
int8 | int | |
uint32 | int | |
NaN | float("nan") | |
Inf | float("inf") | |
string scalar | str | Use Python str Variables in MATLAB |
<missing> value in string | None | py.list({string(missing),'Value'}) ans = Python list with no properties. [None, 'Value'] |
logical | bool | |
Structure | dict | Use Python dict Variables in MATLAB |
Python object — py.type | type | |
function handle @py.module.function, to Python functions only | module.function | Pass Python Function to Python map Function |
Pass Vectors to Python
double (real) | array.array('d') |
single (real) | array.array('f') |
int8 (real) | array.array('b') |
uint8 (real) | array.array('B') |
int16 (real) | array.array('h') |
uint16 (real) | array.array('H') |
int32 (real) | array.array('i') |
uint32 (real) | array.array('I') |
int64 (real) - Not supported for Python 2.7 on Windows® | array.array('q') |
uint64 (real) - Not supported for Python 2.7 on Windows | array.array('Q') |
double (complex) | memoryview |
logical | memoryview |
char vector | str |
char array containing values greater than 127 (version 2.7 only) | unicode |
cell vector | tuple |
Pass Matrices and Multidimensional Arrays to Python
The Python language provides a protocol for accessing memory buffers like the data stored in a MATLAB array. MATLAB implements this Python buffer protocol for MATLAB arrays so that you can read MATLAB arrays directly from Python code, running in the same process as MATLAB, without copying data.
Many Python functions directly use the MATLAB array from Python without converting it to a native Python type. Some functions might require a specific type, such as numpy.ndarray, or might modify data in the array. These functions might accept the MATLAB array and copy the data into the required type. Other functions might display an error if you do not pass the required type. To pass data to these functions, first create the required Python type from the MATLAB data, then pass it to the Python function. For example, to create array p to pass to a Python function that requires data of type numpy.array, type:
p = py.numpy.array(magic(3))
p = Python ndarray: 8 1 6 3 5 7 4 9 2 Use details function to view the properties of the Python object. Use double function to convert to a MATLAB array.
MATLAB sparse arrays are not supported in Python. See Unsupported MATLAB Types.
Troubleshooting Argument Errors
If a Python function expects a specific Python multidimensional array type such as numpy.ndarray, then MATLAB displays a message with tips about how to proceed. If the problem might be due to passing a matrix or a multidimensional array as an argument, then do the following.
Check the documentation for the Python function and find out the expected type for the argument.
Create a Python object of that type in MATLAB and pass that to the Python function.
For example, suppose that the following code returns an error.
a = [1 2; 3 4]; py.pyfunc(a)
If the documentation of pyfunc specifies that the expected type is numpy.ndarray, then try this conversion:
py.pyfunc(numpy.ndarray(a))
If the error persists, then determine the root cause by checking for additional information in the Python exception.
Automatically Convert Python Types to MATLAB Types
MATLAB automatically converts these data types returned from Python functions into MATLAB types. To convert other types, see Explicitly Convert Python Types to MATLAB Types.
float | double |
complex | Complex double |
int (version 2.7 only). For Python versions 3.x int, you must convert explicitly. See Explicitly Convert Python Types to MATLAB Types. | int64 |
bool | logical |
All other Python types — type | Python object — py.type |
Explicitly Convert Python Types to MATLAB Types
If the output of a Python function implements the Python buffer protocol, such as numpy.ndarray, and it is numeric or logical, then MATLAB displays:
The actual Python type
The underlying data
The corresponding MATLAB conversion function. Use this function to fully convert the Python object to a MATLAB array.
Use these MATLAB functions to convert Python data types to MATLAB types.
py.str (version 3.x) | string | Use Python str Variables in MATLAB |
py.str (version 2.7) | string | |
py.unicode | string | |
Object with __str__ method | char | py.help('datetime.date.__str__') Help on wrapper_descriptor in datetime.date: datetime.date.__str__ = __str__(self, /) Return str(self). d = py.datetime.date(... int32(2020),int32(3),int32(4)); char(d) ans = '2020-3-04' |
py.int | Numeric functions: | |
logical | ||
py.bytes | uint8 | |
py.array.array You can convert py.array.array of any format and py.memoryview objects to the MATLAB type you want. | Numeric functions: | Use Python Numeric Variables in MATLAB, for example, Use Python Integer array Types in MATLAB. |
py.list and py.tuple | double | Use Python list Variables in MATLAB For more information, see Error Converting Elements of list or tuple. |
Mapping protocol; for example, py.dict | struct | Use Python dict Variables in MATLAB |
For example, a Python function returns this array p:
p = Python ndarray: 8 1 6 3 5 7 4 9 2 Use details function to view the properties of the Python object. Use double function to convert to a MATLAB array.
You can convert it to a MATLAB matrix P by typing:
P = 3×3 8 1 6 3 5 7 4 9 2
If you need specific information about the Python properties of p, type:
py.numpy.ndarray handle with properties: T: [1×1 py.numpy.ndarray] base: [1×1 py.NoneType] ctypes: [1×1 py.numpy.core._internal._ctypes] data: [1×3 py.memoryview] dtype: [1×1 py.numpy.dtype[float64]] flags: [1×1 py.numpy.flagsobj] flat: [1×1 py.numpy.flatiter] imag: [1×1 py.numpy.ndarray] itemsize: [1×1 py.int] nbytes: [1×1 py.int] ndim: [1×1 py.int] real: [1×1 py.numpy.ndarray] shape: [1×2 py.tuple] size: [1×1 py.int] strides: [1×2 py.tuple] Methods, Events, Superclasses
If the Python module provides content in its __doc__ attribute, then MATLAB links to that information.
Do Not Use Python Objects as Dictionary Keys
You cannot pass a Python object as a key argument to the MATLAB dictionary function or as input to the keyMatch function.
Unsupported MATLAB Types
These MATLAB types are not supported in Python.
Multidimensional char or cell arrays
Structure arrays
Sparse arrays
categorical,
table,
containers.Map,
datetime typesMATLAB objects
meta.class (py.class)
Related Topics
- Use Python Numeric Variables in MATLAB
- Use Python str Variables in MATLAB
- Use Python list Variables in MATLAB
- Use Python tuple Variables in MATLAB
- Use Python dict Variables in MATLAB