kimiya_Ab
kimiya_Ab

Reputation: 31

How to pass cell array from matlab to python?

I have cell array in the result of my coding in Matlab and I want to use this result inside my code in the Python. I there any way to pass the Cell array from Matlab to Python? my cell array contains 2 columns and 45 rows. first columns contain names and the other contains another cell array of 2number. for example, one line in this cell array can be like this if one opens it in MATLAB: 'Pit' 25x2 double

Upvotes: 1

Views: 869

Answers (1)

jmd_dk
jmd_dk

Reputation: 13090

Here's a solution for non-nested cell arrays. It works by writing out the content of the cell array to a file which is then read by Python.

Matlab code

The cell2pylist is where the magic happens, but I've included a main function as well.

function main
% Generate some random 2D cell array
c = cell(4, 3);
for i = 1:numel(c)
    c{i} = rand();
end
c{2} = []; c{5} = 'hello'; c{11} = 42;

% Dump as literal Python list
cell2pylist(c, 'data.txt')
end

function cell2pylist(c, filename)
c = permute(c, ndims(c):-1:1);
% Get str representationelement
output = '';
for i = 1:numel(c)
    if isempty(c{i})
        el = 'None';
    elseif ischar(c{i}) || isstring(c{i})
        el = ['"', char(string(c{i})), '"'];
    elseif isa(c{i}, 'double') && c{i} ~= int64(c{i})
        el = sprintf('%.16e', c{i});
    else
        el = [char(string(c{i}))];
    end
    % Add to output
    output = [output, el, ', '];
end
output = ['[', output(1:end-1), ']'];
% Print out
fid = fopen(filename, 'w');
fprintf(fid, '%s\n', output);
fclose(fid);
end

This will store literal Python list representation of the cell array in the file data.txt.

The block of if statements takes care converting different element types to its string representation. Here you could add a new entry for cell arrays and utilize recursion, if you really need nested cell arrays.

Python code

Now to read in the "cell array" from Python, do

import ast, numpy as np
shape = (4, 3)
c = np.array(ast.literal_eval(open('data.txt').read()), dtype=object).reshape(shape)
print(c)

Upvotes: 1

Related Questions