Arrays mat2str对单元阵列的推广

Arrays mat2str对单元阵列的推广,arrays,string,matlab,octave,cell-array,Arrays,String,Matlab,Octave,Cell Array,我有时会错过一个函数来生成(可能是嵌套的)单元格数组的字符串表示形式。它是的泛化,仅适用于非单元数组(数字、字符或逻辑类型) 给定一个数组x,如何获得字符串表示形式y,从而计算该字符串生成x 例如,输入 x = {[10 20], {'abc'; false; true;}}; 应该生成一个输出字符串,如 y = '{[10 20], {''abc''; false; true}}'; (或关于分离器间距的一些变化),以便 isequal(x, eval(y)) 如果true以下函数适用于

我有时会错过一个函数来生成(可能是嵌套的)单元格数组的字符串表示形式。它是的泛化,仅适用于非单元数组(数字、字符或逻辑类型)

给定一个数组
x
,如何获得字符串表示形式
y
,从而计算该字符串生成
x

例如,输入

x = {[10 20], {'abc'; false; true;}};
应该生成一个输出字符串,如

y = '{[10 20], {''abc''; false; true}}';
(或关于分离器间距的一些变化),以便

isequal(x, eval(y))

如果
true

以下函数适用于具有任何嵌套结构的任意阵列和阵列的任何形状,只要它们都是二维阵列。不支持多维数组(与
mat2str
相同)

该函数还允许为单元格数组指定任意行分隔符和列分隔符(例如,在逗号和空格之间进行选择),并可以选择为非单元格数组强制使用这些分隔符(从而覆盖
mat2str
”行为)。单元格数组中的默认分隔符是列和列的
'
;'用于行

function y = array2str(x, col_sep, row_sep, sep_noncell)
% Converts a (possibly cell, nested) array to string representation
%
% Optional inputs col_sep and row_sep specify separators for the cell arrays.
% They can be arbitrary strings (but they should be chosen as per Matlab rules
% so that the output string evaluates to the input). Optional flag sep_noncell
% can be used to force those separators with non-cell arrays too, instead of
% the separators produced by mat2str (space and semicolon)

% Default values
if nargin<4
    sep_noncell = false;
end
if nargin<3
    row_sep = '; ';
end
if nargin<2
    col_sep = ' ';
end

x = {x}; % this is to initiallize processing
y = {[]}; % [] indicates content unknown yet: we need to go on
done = false;
while ~done
    done = true; % tentatively
    for n = 1:numel(y);
        if isempty(y{n}) % we need to go deeper
            done = false;
            if ~iscell(x{1}) % we've reached ground
                s = mat2str(x{1}); % final content
                if sep_noncell % replace mat2str's separators if required
                    s = regexprep(s,'(?<=^[^'']*(''[^'']*'')*[^'']*) ', col_sep);
                    s = regexprep(s,'(?<=^[^'']*(''[^'']*'')*[^'']*);', row_sep);
                end
                y{n} = s; % put final content...
                x(1) = []; % ...and remove from x
            else % advance one level
                str = ['{' repmat([{[]}, col_sep], 1, numel(x{1})) '}'];
                ind_sep = find(cellfun(@(t) isequal(t, col_sep), str));
                if ~isempty(ind_sep)
                    str(ind_sep(end)) = []; % remove last column separator
                    ind_sep(end) = [];
                end
                step_sep = size(x{1}, 2);
                str(ind_sep(step_sep:step_sep:end)) = {row_sep};
                y = [y(1:n-1) str y(n+1:end)]; % mark for further processing...
                x = [reshape(x{1}.', 1, []) x(2:end)]; % ...and unbox x{1},
                    % transposed and linearized
            end
        end
    end
end
y = [y{:}]; % concatenate all strings
工作原理 我选择了一种非递归的方法,因为我通常更习惯于迭代而不是递归

通过在单元格数组(
y
)中保留子字符串或空数组(
[]
)逐渐构建输出。
y
单元格中的空数组表示“需要进一步处理”。子字符串定义“结构”,或最终定义单元嵌套最深层的数字、字符或逻辑内容

在每次迭代中,在
y
中找到的第一个空数组被实际内容或子字符串和其他稍后处理的空数组替换。当
y
不包含任何空数组时,进程结束,并将
y
的所有子字符串连接起来以获得最终字符串输出

例如,给定输入
x={[1020],{'abc';false;true;}
并调用
y=array2str(x)
每个步骤中的数组
y
是一个单元格数组,包含:

'{'   []   ', '   []   '}'

'{'   '[10 20]'   ', '   []   '}'

'{'   '[10 20]'   ', '   '{'   []   '; '   []   '; '   []   '}'   '}'

'{'   '[10 20]'   ', '   '{'   ''abc''   '; '   []   '; '   []   '}'   '}'

'{'   '[10 20]'   ', '   '{'   ''abc''   '; '   'false'   '; '   []   '}'   '}'

'{'   '[10 20]'   ', '   '{'   ''abc''   '; '   'false'   '; '   'true'   '}'   '}'
最后将后者连接到字符串中

'{[10 20] {''abc''; false; true}}'
作为自定义分隔符的示例,
array2str(x,,,,;,true)
将给出

'{[10, 20], {''abc''; false; true}}'

这个过程将数据结构转换为一个字符串,以后可以对其求值,这个过程被命名为

有一个可用于此目的的应用程序,它支持任何维度数(不仅是2d)的任何核心数据类型(不仅是单元阵列)

示例:

## Works for normal 2d numeric arrays
octave> a = magic (4);
octave> serialize (a)
ans = double([16 2 3 13;5 11 10 8;9 7 6 12;4 14 15 1])
octave> assert (eval (serialize (a)), a)

## Works for normal 3d numeric arrays with all precision
octave> a = rand (3, 3, 3);
octave> serialize (a)
ans = cat(3,double([0.53837757395682650507 0.41720691649633284692 0.66860079620859769189;0.018390655109800025518 0.56538265981533797344 0.20709955358395887304;0.86811365238275806089 0.18398187533949311723 0.20280927116918162634]),double([0.40869259684132724919 0.96877003954154328191 0.32138458265911834522;0.37357584261201565168 0.69925333907961184643 0.10937000120952171389;0.3804633375950405294 0.32942660641033155722 0.79302478034566603604]),double([0.44879474273802461015 0.78659287316710135851 0.49078191654039543534;0.66470978375890155121 0.87740365914996953922 0.77817214018098579409;0.51361398808500036139 0.75508941052835898411 0.70283088935085502591]))
octave> assert (eval (serialize (a)), a)

## Works for 3 dimensional cell arrays of strings
octave> a = reshape ({'foo', 'bar' 'qux', 'lol', 'baz', 'hello', 'there', 'octave'}, [2 2 2])
a = {2x2x2 Cell Array}
octave> serialize (a)
ans = cat(3,{["foo"],["qux"];["bar"],["lol"]},{["baz"],["there"];["hello"],["octave"]})
octave> assert (eval (serialize (a)), a)

然而,一个更好的问题是?如果您这样做的原因是在倍频程的多个实例之间发送变量,请考虑使用具有专门为此目的而设计的函数和包。我不知道这个存在于八度音阶中。它支持多维数组!我只是想用它来更好地控制单元格数组的显示方式,主要是针对@LuisMendo,我刚刚在#octave上与Andy(serialize函数的作者)讨论了对其函数的一些可能改进。您可以创建一个1D向量,然后
重塑
,而不是嵌套调用
cat
。原因是重塑是一个非常便宜的操作,而多个
cat
将导致大量的复制开销。
## Works for normal 2d numeric arrays
octave> a = magic (4);
octave> serialize (a)
ans = double([16 2 3 13;5 11 10 8;9 7 6 12;4 14 15 1])
octave> assert (eval (serialize (a)), a)

## Works for normal 3d numeric arrays with all precision
octave> a = rand (3, 3, 3);
octave> serialize (a)
ans = cat(3,double([0.53837757395682650507 0.41720691649633284692 0.66860079620859769189;0.018390655109800025518 0.56538265981533797344 0.20709955358395887304;0.86811365238275806089 0.18398187533949311723 0.20280927116918162634]),double([0.40869259684132724919 0.96877003954154328191 0.32138458265911834522;0.37357584261201565168 0.69925333907961184643 0.10937000120952171389;0.3804633375950405294 0.32942660641033155722 0.79302478034566603604]),double([0.44879474273802461015 0.78659287316710135851 0.49078191654039543534;0.66470978375890155121 0.87740365914996953922 0.77817214018098579409;0.51361398808500036139 0.75508941052835898411 0.70283088935085502591]))
octave> assert (eval (serialize (a)), a)

## Works for 3 dimensional cell arrays of strings
octave> a = reshape ({'foo', 'bar' 'qux', 'lol', 'baz', 'hello', 'there', 'octave'}, [2 2 2])
a = {2x2x2 Cell Array}
octave> serialize (a)
ans = cat(3,{["foo"],["qux"];["bar"],["lol"]},{["baz"],["there"];["hello"],["octave"]})
octave> assert (eval (serialize (a)), a)