fprintf to txt output

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)

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

Not 100% what you mean. So I should write it all to a table then display the table as txt?
The values for a.Tal and r.Ran don't seem to be the right values anymore either.
I've got that sorted.
Now I just need to work out how to write the table to a txt file in a relative path. For example, where the main file is held....
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.

Sign in to comment.

Products

Asked:

on 27 Aug 2019

Commented:

on 27 Aug 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!