Effacer les filtres
Effacer les filtres

How to print a text file in MATLAB?

48 vues (au cours des 30 derniers jours)
Phan
Phan le 21 Août 2014
Commenté : Geoff Hayes le 21 Août 2014
Dear everyone,
Please help me to solve this problem. I have 2 array and a cell like this:
State=[1 2 3];
Angle=[25 20 13];
Name={'ABC-820' 'S815' 'EG813'};
I want to create a text file like this:
State Name Angle
1 ABC-820 25
2 S815 20
3 EG813 13
Can anyone help me to write a code to make that file?
Thank you so much!

Réponse acceptée

Geoff Hayes
Geoff Hayes le 21 Août 2014
Phan - since you want to create a text file, then use fopen as
fid = fopen('myData.txt','w');
where fid is the file descriptor. If it is positive, then you can write data to file
if fid > 0
% do stuff
% close file
fclose(fid);
end
Since the file has been opened, once we have finished with it, we need to close it with fclose. That leaves the do stuff part of the above code - this is where you write out the data line by line
% write the header (tab-delimited columns)
fprintf(fid,'State\tName\tAngle\n');
% write each row
for k=1:length(State)
fprintf(fid,'%d\t%s\t%d\n',State(k),Name{k},Angle(k));
end
Put it together, and give it a go.
----------------------------
An alternative, if you have a more recent version of MATLAB, is to convert the data to a table and then just write the table to file with writetable
tableData = table(State',Name',Angle','VariableNames',{'State','Name','Angle'})
writetable(tableData,'myTableData.txt','Delimiter','\t');
Try either of the above options and see what happens!
  4 commentaires
Phan
Phan le 21 Août 2014
Oh, I did it!
Thank you so so much!!!
Geoff Hayes
Geoff Hayes le 21 Août 2014
Glad that it worked!

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by