MATLAB Answers

Creating .txt file with matlab

1,713 views (last 30 days)
Pedro Silva
Pedro Silva on 22 May 2012
Commented: Carlos José on 13 Mar 2019
Hey everyone.
I have a function that analyses an image and returns numerical values about it in several variabels.
Imagine I run my code and have the following data
a1=2; a2=4; a3=0; a4=8;
now I want my code to write this values in a .txt in the following way: 2,4,0,8
I want to be capable of analysing several images in the folder and to keep all the results in the same .txt file, with all the values separated by commas.
Thanks in advance!

  0 Comments

Sign in to comment.

Accepted Answer

Geoff
Geoff on 22 May 2012
This opens the file once (overwriting if it already exists) and writes your results one line at a time.
fid = fopen( 'results.txt', 'wt' );
for image = 1:N
[a1,a2,a3,a4] = ProcessMyImage( image );
fprintf( fid, '%f,%f,%f,%f\n', a1, a2, a3, a4);
end
fclose(fid);
Alternatively, you could open the file in 'append' mode, write the line, and close it again each time through the loop.
doc fopen

  2 Comments

Charles Miller
Charles Miller on 6 Feb 2019
Okay, but how do you CREATE the file to output to?
Carlos José
Carlos José on 13 Mar 2019
This code already creates one txt file...
you can see it better using this code (try it on your matlab):
b = [65 66 67 68 69];
criptografia = char(b);
fid = fopen('output.txt','wb');
fwrite(fid, criptografia, 'char');
fclose(fid);

Sign in to comment.

More Answers (1)

David Fernández
David Fernández on 23 May 2017
Thanks! Simple, usefull.

  0 Comments

Sign in to comment.

Sign in to answer this question.