如何为现有 'Cell Arrays' MATLAB 获取命令 Window 格式

How to get Command Window format for existing 'Cell Arrays' MATLAB

我创建了一个元胞数组,我想获取该元胞数组的命令 window 格式。

例如:我使用命令行创建了一个 5x2 元胞数组:

MyCell = {'time' , 'timestamp';'posX', {'DePositionX', 'DePositionXmm'};'posY',  {'DePositionY', 'DePositionYmm'};'velocityX', 'DeVelocityX';'velocityY', 'DeVelocityY'};

同样,我已经创建了一个 MxN 元胞数组(不是我创建的),我想以命令 window 格式获取该元胞的结构,如上面的代码所示。你能告诉我有什么方法或命令可以得到这个吗?

谢谢。

这是一个可以完成您想要的功能的函数。它是 Per-Anders Ekstrom 的 cell2str (https://www.mathworks.com/matlabcentral/fileexchange/13999-cell2str) 的递归版本。它至少应该适用于单元格数组,其元素(递归地)是单元格、字符、数字或逻辑类型。

function s = cell2str(C)

% input checking
if ~iscell(C) || ~ismatrix(C)
    error('Input must be a 2-d cell array');
end

% get size of input
S = size(C);

% transpose input so will be traversed in rows then columns
C = C.';

% initialize output string with open bracket
s = '{';

% iterate over elements of input cell
for e = 1:numel(C)
    if ischar(C{e}) % if element is char, return a string that will evaluate to that char
        s = [s '''' strrep(C{e},'''','''''') ''''];
    elseif iscell(C{e}) % if element is cell, recurse
        s = [s cell2str(C{e})];
    else % if element is not char or cell, try to convert it using mat2str
        s = [s mat2str(C{e})];
    end
    % add a semicolon if at end of row or a comma otherwise
    if mod(e, S(2))
        s = [s ','];
    else
        s = [s ';'];
    end
end

% complete output string with closing bracket
s = [s '}'];

要使用您提供的元胞数组进行检查,语句

isequal(MyCell, eval(cell2str(MyCell)))

计算结果为真。