How to print a text file in MATLAB?

82 views (last 30 days)
Phan
Phan on 21 Aug 2014
Commented: Geoff Hayes on 21 Aug 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!

Accepted Answer

Geoff Hayes
Geoff Hayes on 21 Aug 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 Comments
Phan
Phan on 21 Aug 2014
Oh, I did it!
Thank you so so much!!!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!