Is it right this way?

7 views (last 30 days)
Francesco
Francesco on 21 Feb 2014
Commented: Walter Roberson on 22 Feb 2014
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
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.
  2 Comments
Francesco
Francesco on 22 Feb 2014
You have put .' and dpb has put only '. Can I know the difference between this two situation?

Sign in to comment.


dpb
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
Walter Roberson
Walter Roberson on 22 Feb 2014
What have you corrected the dlmwrite() call to now be?
Walter Roberson
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!