Search code examples
matlabcell-array

display all elements in a nested cell array (with integer entries)


This is related to the post

display all elements in a nested cell array (with character entries)

with a change where entries are characters. A new question was asked for clarity.

Now :

a =

{1x10 cell}    {1x10 cell}    {1x10 cell}    {1x10 cell}

a{:}=

ans = [0]    [0.4000]    [0]    [0]    [0]    [0]    [0]    [0]    [0]    [0]

ans = [0]    [0]    [0.2000]    [0]    [0.2000]    [0]    [0.2000]    [0]    [0]    [0]

ans = [0]    [0]    [0]    [0]    [0]    [0.2000]    [0]    [0]    [0.2000]    [0.2000]

ans = [0]    [0.2000]    [0]    [0]    [0]    [0]    [0]    [0.4000]    [0]    [0.2000]

the answer to the previous was:

fileID = fopen('a.txt', 'at');
fprintf(fileID, '%2.8s \n', cellfun(@(x) char(x), a));
fclose(fileID);

How to solve it now? want to print:

           0  0.4  0    0  0   0  0   0  0  0
           0  0    0.2  0  0.2 0  0.2 0  0  0
           .
           . 

thanks


Solution

  • This is one way to do it:

    a = { { 0, 0.4000, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0.2000, 0, 0.2000, 0, 0.2000, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0.2000, 0, 0, 0.2000, 0.2000 }, { 0, 0.2000, 0, 0, 0, 0, 0, 0.4000, 0, 0.2000 }};
    
    fileID = fopen('a.txt', 'at');
    
    fprintf(fileID, [ (regexprep((regexprep((regexprep((regexprep(mat2str(cell2mat(cellfun(@cell2mat, a, 'UniformOutput', false)')), '(0 )' , '$1  ')), '[', '')), ']', '')), ';', '\n')), '\n' ]);
    
    fclose(fileID);
    

    Edit: alternative solution. In this one shorter lines are padded with spaces.

    CharMatrix = char(regexprep(cellfun(@mat2str, (cellfun(@cell2mat, a, 'UniformOutput', false)'), 'UniformOutput', false), '0 ', '0   '));
    CharMatrix(CharMatrix == ']') = ' ';
    CharMatrix(:,1) = [];
    CharMatrix(:,end) = '\';
    CharMatrix(:,end+1) = 'n';
    fileID = fopen('a.txt', 'at');
    fprintf(fileID, reshape(CharMatrix', 1, []));
    fclose(fileID);