Writing table data into text file. Adapt data from a table to write it into the "mid" section of a text file!

조회 수: 5 (최근 30일)
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
Sindar
Sindar 2020년 10월 28일
% 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})
Siegfried Suthau
Siegfried Suthau 2020년 10월 28일
This is it. I mishandled my table and the convertCharsToStrings function helped!
Thank you very much, for your time and effort!

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 String에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by