Search code examples
filematlabcell

MATLAB: Write strings and numbers of variables in files


I have following data:

a=[3 1 6]';
b=[2 5 2]';
c={'ab' 'bc' 'cd'}';

I now want to make a file which looks like this (the delimiter is tab):

ab    3    2
bc    1    5 
cd    6    2

my solution (with a loop) is:

a=[3 1 6]';
b=[2 5 2]';
c={'ab' 'bc' 'cd'}';
c=cell2mat(c);
fid=fopen('filename','w');
for i=1:numel(b)

    fprintf(fid,'%s\t%u\t%u\n',c(i,:),a(i),b(i));

end

fclose(fid);

Is there a possibility without loop and/or the possibility to write cell arrays directly in files?

Thanks.


Solution

  • How about this:

    %A cell array holding all data
    %    (Note transpose)
    data = cat(2, c, num2cell(a), num2cell(b))';
    

    Write data to a file

    fid = fopen('example.txt', 'w');
    fprintf(fid, '%s\t%u\t%u\n', data{:});
    fclose(fid);
    

    This will be memory wasteful if your datasets get large (probably better to leave then as separate variables and loop), but seems to work.