6

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 would I write the data in 'Final' into a tab delimited text file. I know how to use fopen, fprintf and so on when the variable is composed of solely numerical inputs but am struggling to solve this problem. I have tried:

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

However, this does not generate a text file that is in the same format as that generated in matlab. How can this problem be solved?

1
  • +1 for the easily workable code you provided Commented Jan 8, 2013 at 12:13

1 Answer 1

6

This solution gives what I think you need; some remarks which I hope to be useful are on 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 a N-columns cell, you can simply go for a for loop, e.g.

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

Great answer, although what would happen if the cell array had more than 2 column e.g. 10 columns, would that involve writing Final(:,1),Final(:,2),Final(:,3) and so on. There must be a method where this works without specifying the individual columns?
@Kate, sure. Indeed what cellfun does is just wrapping a for loop, in this case for the rows. What you can do is to write your own for loops involving the columns also. I'm changing the answer for the general case.
@Kate, please have a look.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.