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
下面是一个非嵌套单元格数组的解决方案。它的工作原理是将单元数组的内容写入一个文件,然后由Python读取。在
Matlab代码
cell2pylist
是魔术发生的地方,但我也包含了一个main函数。在这将在文件
data.txt
中存储单元数组的文本Python列表表示。在if
语句块负责将不同的元素类型转换为其字符串表示形式。如果您真的需要嵌套的单元数组,您可以在这里为单元数组添加一个新条目并利用递归。在Python代码
现在要读入Python中的“cell array”,请执行以下操作
^{pr2}$相关问题 更多 >
编程相关推荐