fprintf to txt output
Show older comments
I have 3 columns of data that I am trying to output to a txt file, however, the output I get is not in 3 columns and is complete gibberish.
A = datestr((t.Time), 'MM:SS.FFF');
B = num2str(a.Tal);
C = num2str(r.Ran);
fid=fopen('C:\Users\Aaron\Desktop\myfile.txt','wt');
fprintf(fid, '%s %f %f r\n', [A,B,C]);
fclose(fid);true
Also, how would I change this to save to the same path the open file is in so that it can work on any computer?
Cheers,
Aaron
Answers (1)
Star Strider
on 27 Aug 2019
The problem is that to use fprintf with mixed data types (here a string and two apparently double-precision vectors), you need to use a loop:
for k = 1:size(A,1)
fprintf(fid, '%s %f %f r\n', A(k,:),B(k),C(k));
end
There are easier options, such as writematrix and if you create a table from your variables first, writetable (linked to at the end of that documentation page).
3 Comments
Aaron Fiddler
on 27 Aug 2019
Aaron Fiddler
on 27 Aug 2019
Star Strider
on 27 Aug 2019
The loop should work with your original fprintf statement to produce the file you want.
‘The values for a.Tal and r.Ran don't seem to be the right values anymore either.’
When I ran my code with my test data, the loop printed the times and vectors correctly. Without your structures, I cannot suggest a correct way of printing them. I have no idea what they contain.
With regard to creating a table, that is simply an option. The struct2table function could help, as well as creating your times as a datetime array. or put everything together in a timetable. I have no idea what you want to do, so I’m just suggesting options.
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!