Writing table data into text file. Adapt data from a table to write it into the "mid" section of a text file!
5 views (last 30 days)
Show older comments
Hello everyone!
I import excel data with the readtable function and I would like to adapt this data slightly for export in a text file.
Following you will find an example code:
t=table( 0 ,5, 6 ,3, 1)
fid = fopen("loop_test.mos",'wt+');
first_base_text="This is a basic text I want to add to the beginning of the file.\nTesting of new line"
fprintf(fid, first_base_text)
%fprintf(fid,t)
last_base_text="This is the text i want to add at the end"
fprintf(fid,last_base_text)
fclose(fid)
And the example text file should look like this:
-------------------------------------------------------------
This is a basic text I want to add to the beginning of the file.
Testing of new line;
t={0,5,6,3,1}
This is the text I want to add to the end of the file.
----------------------------------------------------------------
The code should be able to handle different sizes of table, because the table size depends on the input via excel import.
I just do not get an idea on how to handle this eloquently. I hope that you are able to offer me some support!
Best regards and thank you very much
9 Comments
Sindar
on 28 Oct 2020
% this produces a table with one column per input
t=cell2table({'Cvode','Cvode' ,'Cvode','Euler','Euler','Euler','Dassl','Dassl','Dassl'})
fprintf(fid,'t={')
% convertCharsToStrings does what it says on the tin,
% and fprintf accepts string arrays
fprintf(fid,'"%s",',convertCharsToStrings(t{:,1:end-1}))
fprintf(fid,'"%s"}',convertCharsToStrings(t{:,end}))
producing:
t={"Cvode","Cvode","Cvode","Euler","Euler","Euler","Dassl","Dassl","Dassl"}
alternatively, if you have the cell array as a variable, you can convert it while making the table:
mystr = {'Cvode','Cvode' ,'Cvode','Euler','Euler','Euler','Dassl','Dassl','Dassl'};
t=array2table(convertCharsToStrings(mystr));
fprintf(fid,'t={')
fprintf(fid,'"%s",',t{:,1:end-1})
fprintf(fid,'"%s"}',t{:,end})
Answers (0)
See Also
Categories
Find more on String 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!