1

I have a Cell-array created and i want to get the command window format for that cell-array.

For example: I have created a 5x2 cell array using command line:

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

Similarly I have a MxN cell array already created(not by me) and i want to get the structure of that cell in a command window format as shown in the above code. Can you tell me is there any way or commands to get this.

Thanks.

Ganesh H
  • 45
  • 6

1 Answers1

0

Here's a function that should accomplish what you want. It's a recursive version of Per-Anders Ekstrom's cell2str (https://www.mathworks.com/matlabcentral/fileexchange/13999-cell2str). It should work at least with cell arrays whose elements are (recursively) of type cell, char, numeric, or logical.

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 '}'];

To check it with the cell array you provided, the statement

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

evaluates to true.

verbatross
  • 607
  • 1
  • 5
  • 10