How to save an fprintf command to a variable?

80 views (last 30 days)
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 Comments
Stephen23
Stephen23 on 15 Feb 2015
Edited: Stephen23 on 16 Feb 2015
"I get ... one number as my answer": yes, because that is exactly what the fprintf documentation says will happen: it returns the bytes written.
Gramotey
Gramotey on 23 Mar 2016
Edited: John Kelly on 1 Feb 2017
I am also a newbie. Use sprintf() to print into a string (make array of strings).

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 15 Feb 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 Comment
Guillaume
Guillaume on 15 Feb 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.

Sign in to comment.


Kayuri Shah
Kayuri Shah on 16 Feb 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.

Community Treasure Hunt

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

Start Hunting!