Is it right this way?
Show older comments
I have a intpts variable:
intpts
intpts =
30.0000 20.0000
28.7500 17.5000
28.0000 16.0000
27.5000 15.0000
31.0000 22.0000
32.5000 17.5000
30.0000 15.0000
28.7500 13.7500
35.0000 20.0000
36.2500 21.2500
32.5000 13.7500
I would like to create a .txt file that contains the previous number. Is it right to do this?
nomefile = fopen ( 'file.txt' , 'wt');
fprintf ( nomefile , '%6.2g %8.4g\n' , intpts);
fclose (nomefile);
Is there another way to do this in a simple or more effective metod? What do you suggest?
Answers (2)
Walter Roberson
on 21 Feb 2014
fprintf ( nomefile , '%6.2g %8.4g\n' , intpts.');
You could also use csvwrite() or dlmwrite().
In time you may find yourself migrating back to the fopen/fprintf/fclose version, due to the extra control it gives you about choosing formats column by column, and for putting in headers and for writing multiple variables.
dpb
on 21 Feb 2014
Other than you need a transpose operator (') on the array to write in row-major order --
fprintf(nomefile ,'%6.2g %8.4g\n',intpts');
That's not terribly onerous is it?
The alternative could be dlmwrite which lets you use the file name instead of file handle which is kinda convenient but it doesn't allow more than one format for the full output so your case of wanting different format by column can't be handled.
dlmwrite('file.txt',intpts,'delimiter',' ','precision','%.4f')
It also handles the transpose transparently being a higher-level abstraction of fprintf
But, outside that, if you want a specific output format, you specify it, yes...
6 Comments
Francesco
on 22 Feb 2014
Francesco
on 22 Feb 2014
Walter Roberson
on 22 Feb 2014
The first five inputs are expected to be filename,M,delimiter,row,col so it appears that you are attempting to pass ' ' for the row parameter and '%10.5f' as the column parameter. Those must be numeric when they are supplied.
In dpb's answer the word 'delimiter' is a keyword, and 'precision' is a keyword.
dlmwrite() only allows you to pass one 'precision' string. If you need different formats for different columns then don't use dlmwrite()
Francesco
on 22 Feb 2014
Walter Roberson
on 22 Feb 2014
What have you corrected the dlmwrite() call to now be?
Walter Roberson
on 22 Feb 2014
I'm going to bed now. If you want to keep fighting your code so you can take advantage of the "simplicity" of dlmwrite() instead of the "complexity" of fopen() fprintf() fclose(), then feel free to do so.
Categories
Find more on Low-Level File I/O in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!