Main Content

Use Python tuple Variables in MATLAB

This example shows how to use Python® tuple variables in MATLAB®.

Call Python Function That Takes tuple Input Arguments

The Python version 2.7 function cmp(a,b) compares two tuple values. To call cmp, either pass a MATLAB cell array or create a tuple by calling the py.tuple command.

Create a tuple variable to pass to a Python function.

pStudent = py.tuple({'Robert',19,'Biology'})
pStudent = 
  Python tuple with no properties.

    ('Robert', 19.0, 'Biology')

Create an equivalent cell array.

mStudent = {"Robert",19,"Biology"}
mStudent=1×3 cell array
    {["Robert"]}    {[19]}    {["Biology"]}

Compare the tuple value to the MATLAB cell array value. The output is -1 if a<b, 0 if a=b, or 1 if a>b. The values are equivalent.

pe = pyenv;
if pe.Version == "2.7"
    py.cmp(pStudent, mStudent)
end

Convert tuple to MATLAB variable

To convert a tuple to a MATLAB cell array, call the cell function.

S = cell(pStudent)
S=1×3 cell array
    {1×6 py.str}    {[19]}    {1×7 py.str}

Read Elements in tuple

Use MATLAB indexing to display elements in a tuple. For example, display the first two elements of pStudent. MATLAB returns a tuple variable.

pStudent(1:2)
ans = 
  Python tuple with no properties.

    ('Robert', 19.0)

Display one element. MATLAB returns a Python data type element.

pStudent{3}
ans = 
  Python str with no properties.

    Biology

Create tuple Containing Single Element

Create a tuple variable with a single element. MATLAB displays a trailing comma for a tuple with one element.

subject = py.tuple({'Biology'})
subject = 
  Python tuple with no properties.

    ('Biology',)