1

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

Community
  • 1
  • 1
pac
  • 291
  • 9
  • 19

2 Answers2

2

I seem to recall if you put the values into an array, it will do the conversion appropriately. I don't have Matlab to test it, but this should work.

[a{:}]
PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142
1

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);
nrz
  • 10,435
  • 4
  • 39
  • 71