How to save an fprintf command to a variable?
16 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I am using the fprintf function to display a column of values from a matrix assigned "Summary1." I would like to assigned a variable "a" to whatever the fprintf command displays. Using the code below displays the values in the command window just fine:
Summary1 =
100.0000 0.0000
150.0000 0.0000
200.0000 0.0000
250.0000 0.0001
300.0000 0.0018
350.0000 0.0121
400.0000 0.0510
450.0000 0.1561
500.0000 0.3820
fprintf ('%u %1.2e \n', [Summary1]')
=
100 3.92e-15
150 2.64e-09
200 2.17e-06
250 1.22e-04
300 1.78e-03
350 1.21e-02
400 5.10e-02
450 1.56e-01
500 3.82e-01
However, when I put in
a = fprintf ('%u %1.2e \n', [Summary1]')
I get "a = #" one number as my answer. Is there a way I can assign a one letter variable to this fprintf command and have it output my column of values from "Summary1"?
Thanks!
2 comentarios
Gramotey
el 23 de Mzo. de 2016
Editada: John Kelly
el 1 de Feb. de 2017
I am also a newbie. Use sprintf() to print into a string (make array of strings).
Respuestas (2)
Image Analyst
el 15 de Feb. de 2015
Use sprintf(), not fprintf() when you want to save the result to a string:
% Save display to a string:
string = sprintf ('%u %1.2e \n', [Summary1]');
% Now print the string to the command window.
fprintf ('%s\n', string);
1 comentario
Guillaume
el 15 de Feb. de 2015
The reason behind the naming of these two functions is that fprintf prints to a file (traditionally, the console / command window has been considered a file), while sprintf prints to a string.
Kayuri Shah
el 16 de Feb. de 2015
The other option is to save your results in a matrix, as you did, and then wait to print until the end. In fprintf, you are just printing to a destination, rather than saving the string to use later. In that case, use fprintf when you are ready to print that section of your work.
Otherwise, save the string in sprintf and then print that to the window you want.
0 comentarios
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!