简体   繁体   English

如何将单元格数组从Matlab传递给python?

[英]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. 我在Matlab中编码的结果中包含单元格数组,我想在Python的代码中使用此结果。 I there any way to pass the Cell array from Matlab to Python? 我有什么方法可以将Cell数组从Matlab传递给Python? my cell array contains 2 columns and 45 rows. 我的单元格数组包含2列和45行。 first columns contain names and the other contains another cell array of 2number. 第一列包含名称,另一列包含另一个2number的单元格数组。 for example, one line in this cell array can be like this if one opens it in MATLAB: 'Pit' 25x2 double 例如,如果在MATLAB中将其打开,则该单元格数组中的一行可能像这样:'Pit'25x2 double

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. 它通过将单元格数组的内容写到一个文件中来工作,然后由Python读取该文件。

Matlab code Matlab代码

The cell2pylist is where the magic happens, but I've included a main function as well. cell2pylist是发生魔术的地方,但是我也包括了一个主要功能。

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 . 这会将单元格数组的文字Python列表表示形式存储在文件data.txt

The block of if statements takes care converting different element types to its string representation. if语句块小心地将不同的元素类型转换为其字符串表示形式。 Here you could add a new entry for cell arrays and utilize recursion, if you really need nested cell arrays. 如果确实需要嵌套的单元格数组,则可以在此处为单元格数组添加一个新条目并利用递归。

Python code Python代码

Now to read in the "cell array" from Python, do 现在要从Python读取“单元格数组”,请执行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM