Write an array of cells of a combined string and numerical input to a text file

Consider the following:

DateTime = {'2007-01-01 00:00';'2007-02-01 00:00';'2007-03-01 00:00'}; Headers = {'Datetime','Data'}; Dat = [100,200,300]; Data = [DateTime,num2cell(Dat')]; Final = [Headers;Data]; 

How to write data in the "Final" in a text file with tab delimiters. I know how to use fopen, fprintf, etc., When a variable consists solely of numerical inputs, but I am trying to solve this problem. I tried:

 fid = fopen('C:\Documents\test.txt','wt'); fprintf(fid,'%s\t%s\n',Final{:}); fclose(fid); 

However, this does not create a text file that is in the same format as MATLAB. How to solve this problem?

+6
source share
1 answer

This solution gives what you think you need; some comments that I hope to be helpful are on the side

  DateTime = {'2007-01-01 00:00';'2007-02-01 00:00';'2007-03-01 00:00'}; Headers = {'Datetime','Data'}; Dat = [100,200,300]; % // In the way you used fprintf it expects just strings ('%s\t%s\n'), % // therefore Data should be composed exclusively by them. % // Numbers are converted to strings by using num2str % // by using cellfun we iteratively convert every element of num2cell(Dat') % // in strings, obtaining a cell Data = [DateTime,cellfun(@num2str, num2cell(Dat'), 'UniformOutput' , false )]; Final = [Headers;Data]; fid = fopen('test.txt','wt'); % // this iterates fprintf on the cell rows, giving you the output cellfun(@(x,y) fprintf(fid,'%s\t%s\n',x,y),Final(:,1),Final(:,2)); fclose(fid); 

result

  Datetime Data 2007-01-01 00:00 100 2007-02-01 00:00 200 2007-03-01 00:00 300 

EDIT: (from comments) in the general case of N-column cells, you can just go into a for loop, for example.

 for i = 1 : size(Final,1) fprintf(fid,'%s ', Final{i,:} ); fprintf(fid,'\n'); end 

(the same result, but does not depend on the number of columns).

+6
source

All Articles