Merge strings and table to one text file using fprintf - Matlab

Viewed 193

How can I save the information generate in the script below which include strings and table in the following format to a text file?

Format:

M=5
1 21
2 22
3 23
4 24
5 25
5points

Script:

clc;
clear all;
close all;

ElmentsNum = "EM=5";
x = (1:5)';
y =(21:25)';
t = table(x,y);
M = "5points"
  
fileID = fopen('E:/Data.txt');
fprintf(fileID,'%s/n',ElmentsNum)
fprintf(fileID,'%.4f',t)
fprintf(fileID,'%s/n',M)
fclose(fileID)
1 Answers

Quite simple, just extract the values of the table, then write them line by line:

extracted_table=table2array(t);

fileID = fopen('Data.txt','w');
fprintf(fileID,'%s\n',ElmentsNum);
for ii=1:size(extracted_table,1)
%     fprintf(fileID,'%.4f %.4f\n',extracted_table(ii,:)); % if you want decimal places
    fprintf(fileID,'%d %d\n',extracted_table(ii,:)); % if you want integers (as in the example)
end
fprintf(fileID,'%s\n',M);
fclose(fileID);
Related