4

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
  • 2
    clear all is very seldomly necessary. clear by itself clears all variables from the workspace, and is what you are attempting to do. clear all also unloads all previously loaded function definitions, meaning that they will all be loaded again when you use them, slowing down your code. Commented Oct 6, 2021 at 14:11

1 Answer 1

5
+25

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);
Sign up to request clarification or add additional context in comments.

2 Comments

%g would give you "The more compact of %e or %f, with no trailing zeros" (from the docs) so that eases the %d/%.4f decision making :)
@Wolfie Good point! As often the code that reads the files may need X amount of floating point precision, I will leave my answer as is, but OP should definitely note your comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.