How can I write different length and different datatypes data to a text file from matlab
4 views (last 30 days)
Show older comments
Right now I can only write a fixed length data to the text file ,but I need to change to a variable length data. My code:
fileID = fopen(logfilePathLocal,'at+');
formatSpec = '%s,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n';
fprintf(fileID,formatSpec,data{1,:});
fclose(fileID);
0 Comments
Accepted Answer
Jan
on 25 Jan 2017
Edited: Jan
on 25 Jan 2017
Width = size(data, 2);
formatSpec = ['%s', repmat(',%d', 1, Width - 1), '\n'];
Or:
fileID = fopen(logfilePathLocal,'at+');
fprintf(fileID, '%s', data{1,1});
fprintf(fileID, ',%d', data{1,2:end});
fprintf(fileID, '\n');
fclose(fileID);
I don't know, what is faster or easier.
More Answers (1)
Walter Roberson
on 24 Jan 2017
You can compute the format specification. I often construct a format using repmat and [] concatenation.
4 Comments
Jan
on 25 Jan 2017
@Walter: Sorry, I have not seen your comment, because I had this thread opened for more than an hour and forgot to press the "relaod" button of my browser. The similarity with your answer was an accident.
See Also
Categories
Find more on Low-Level File I/O in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!