How to save an fprintf command to a variable?

17 Ansichten (letzte 30 Tage)
Andrea Nguyen
Andrea Nguyen am 15 Feb. 2015
Bearbeitet: John Kelly am 1 Feb. 2017
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 Kommentare
Stephen23
Stephen23 am 15 Feb. 2015
Bearbeitet: Stephen23 am 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 am 23 Mär. 2016
Bearbeitet: John Kelly am 1 Feb. 2017
I am also a newbie. Use sprintf() to print into a string (make array of strings).

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Image Analyst
Image Analyst am 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 Kommentar
Guillaume
Guillaume am 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.

Melden Sie sich an, um zu kommentieren.


Kayuri Shah
Kayuri Shah am 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.

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by