How do I save data to a TXT file? I want to create a simple two column text file, where the first column is the data from a n x 1 matrix and the second column is a different n x 1 matrix. I also want column headings in the first row of each column.

댓글 수: 2

Raghunandan V
Raghunandan V 2018년 10월 4일
편집: per isakson 2019년 1월 20일
the problem is you are trying to store them in an array whereas you have to store them in a cell array since each file is of different size Try this code
fileName={'new1.txt', 'new2.txt', 'new3.txt'};
%open file identifier
fid=fopen('MyFile.txt','w');
for k=1:length(fileName)
%read the file name as string including delimiters and next lines
List=textread(fileName{1,k},'%s','delimiter','\n');
%arrange them in order of k if you want in a cell array
FinalList{k,1}=List;
%or print them into a file.
fprintf(fid, [cell2mat(List) '\n']);
end
%close file indentifier
fclose(fid)
Yeswanth Kaushik
Yeswanth Kaushik 2023년 6월 8일
try writetable or writecell commands.

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

 채택된 답변

José-Luis
José-Luis 2024년 9월 4일
편집: MathWorks Support Team 2024년 6월 5일

18 개 추천

To write a text file with columns of data that have variable names, use the “writetable” function. First, create the data to write, put it in a table with variable names, and then write the data to text file.
% Create two columns of data A = rand(10,1); B = rand(10,1); % Create a table with the data and variable names T = table(A, B,'VariableNames',{'A', 'B'}); % Write data to text file writetable(T,'MyFile.txt')
For more information see:
Write table to file
https://www.mathworks.com/help/matlab/ref/writetable.html
Starting in MATLAB R2019a
, you can also use the "writematrix" function to write a matrix to a file. For example:
M = magic(5); writematrix(M,"M.txt");
For a complete list of export functions, see:
Supported File Formats for Import and Export
https://www.mathworks.com/help/matlab/import_export/supported-file-formats-for-import-and-export.html

댓글 수: 13

Bernoulli Lizard
Bernoulli Lizard 2012년 9월 5일
When I to open this file [in Notepad] the format is messed up. Instead of displaying in two columns, it is one long string. How can I make it display as two columns?
Azzi Abdelmalek
Azzi Abdelmalek 2012년 9월 5일
open it with wordpad
José-Luis
José-Luis 2012년 9월 5일
편집: José-Luis 2012년 9월 5일
You just discovered one of the joys of moving files between Unix and Windows: the end-of-line is not the same
Since you use windows, it should work with:
fprintf(fid, '%d %d \r\n', [A B]);
Note that you would also need to modify the first fprintf. Also, notepad is evil.
Bernoulli Lizard
Bernoulli Lizard 2012년 9월 5일
After doing this the data appears to be displayed in two separate columns, but the data is completely jumbled. Some of the x data is in the y column and vice versa. This happens whether I open it in wordpad or in notepad.
José-Luis
José-Luis 2012년 9월 5일
편집: José-Luis 2012년 9월 5일
My bad, %d is the format for integers, you probably want to save floats. If your data are floats, then:
fprintf(fid, '%f %f \r\n', [A B]);
For more info on formats:
doc fprintf
Bernoulli Lizard
Bernoulli Lizard 2012년 9월 5일
편집: Bernoulli Lizard 2012년 9월 5일
That allows it to display more sig figs, but the data is still in the wrong order. It is displaying all of the x data in both columns, and then all of the y data in both columns.
So instead of
1 10
2 20
3 30
4 40
5 50
it is saving it as
1 2
3 4
5 10
20 30
40 50
I have no idea why it would do this or how to fix it.
José-Luis
José-Luis 2012년 9월 5일
편집: José-Luis 2012년 9월 5일
This should work, taking the transpose so the data is in the proper order:
A = (1:10)';
B = (10:10:100)';
header1 = 'Hello';
header2 = 'World!';
fid=fopen('MyFile.txt','w');
fprintf(fid, [ header1 ' ' header2 '\r\n']);
fprintf(fid, '%f %f \r\n', [A B]');
fclose(fid);
Is it possible your data are 1xn rather than nx1? Try this:
fprintf(fid, '%f %f \n', [A(:) B(:)]);
A(:) converts the matrix A into a column vector (which is what you want assuming A is indeed a vector).
Good luck,
Eric
Bernoulli Lizard
Bernoulli Lizard 2012년 9월 5일
Wow, I never thought of just transposing [A B].
Thank you, you're brilliant!
José-Luis
José-Luis 2012년 9월 5일
No worries. I am not so sure about the brilliant part, but I'll make sure to tell my supervisor. :)
% code
A = rand(10,1);
B = rand(10,1);
header1 = 'Hello';
header2 = 'World!';
fid=fopen('MyFile.txt','w');
fprintf(fid, [ header1 ' ' header2 'r\n']);
fprintf(fid, '%f %f r\n', [A B]');
fclose(fid);true
% code
Thanks for the code. Was looking for something exactly like this. May I add that "If you plan to read the file with Microsoft® Notepad, use '\r\n' instead of '\n' to move to a new line." https://www.mathworks.com/help/matlab/ref/fprintf.html
lafnath p
lafnath p 2016년 11월 14일
how to get the size of data in file
celine azizieh
celine azizieh 2017년 8월 14일
Better to use: fid=fopen('MyFile.txt','wt');
instead of fid=fopen('MyFile.txt','w');
otherwise when opening the file with notepad, there is not return to the line... everything is written on one line.

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

추가 답변 (3개)

WAEL Al-dulaimi
WAEL Al-dulaimi 2017년 12월 8일

1 개 추천

In case I want to open a text file and I have a loop that each time give me different results {x1, x1...xn}. So how can I save all the data that I got from the loop in different names such as y1, y2 .... etc? And under each one of them, I can find the result that I got. I'll appreciate your help. thank you

댓글 수: 1

Peter
Peter 2017년 12월 8일
It is unclear form your question what you are trying to loop across. It sounds like your trying to read from a single text file; is this true? In any case you should be able to just assign the value that you read to a new variable. If you know how long each data set is you can preallocate matrices for those variables, but that's not necessarily necessary.

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

Ahmed Saeed Mansour
Ahmed Saeed Mansour 2019년 1월 20일

1 개 추천

How can we save transient CFD results in a file during running the code?

댓글 수: 1

Venkatanarasimha Hegde
Venkatanarasimha Hegde 2023년 3월 17일
Its better if you store the time data at different instants along another matrix dimension (possible in C not sure about matlab) or you can concatinate the new data to existing file, so while visualising you can access after the end index of each time instant.

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

카테고리

도움말 센터File Exchange에서 Language Support에 대해 자세히 알아보기

제품

릴리스

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by