Use Python list Type in MATLAB

This example shows how to display folders on your system using the MATLAB® disp function on the Python® sys.path variable. sys.path is a list type.

Create a Python list, P, of folders on the Python search path.

P = py.sys.path;
class(P)
ans =

py.list

Convert list P to a MATLAB type. The first step is to convert the list to a cell array of folder names, cP.

cP = cell(P);
class(cP)
ans =

cell

Each folder name is a Python string.

class(cP{1})
ans =

py.str

Convert the Python strings in cP to MATLAB data using the char function. Put the values into a new cell array, cellP. Display the folder names.

cellP = cell(1, numel(cP));
for n=1:numel(cP)
    strP = char(cP{n});
    cellP(n) = {strP};
    disp(strP)
end
C:\Python27\lib\site-packages\protobuf-2.5.0-py2.7.egg
C:\windows\system32\python27.zip
C:\Python27\DLLs
C:\Python27\lib
C:\Python27\lib\plat-win
C:\Python27\lib\lib-tk
C:\Python27
C:\Python27\lib\site-packages

MATLAB displays information specific to your Python installation.

Alternatively, create cellP using the cellfun function to combine the conversion functions.

cellP = cellfun(@char,cell(P),'UniformOutput',false);

Display the folder names.

for n=1:py.len(P)
    disp(cellP{n})
end

See Also

|

Related Topics