How to save an fprintf command to a variable?

조회 수: 76 (최근 30일)
Andrea Nguyen
Andrea Nguyen 2015년 2월 15일
편집: John Kelly 2017년 2월 1일
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
Stephen23
Stephen23 2015년 2월 15일
편집: Stephen23 2015년 2월 16일
"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 2016년 3월 23일
편집: John Kelly 2017년 2월 1일
I am also a newbie. Use sprintf() to print into a string (make array of strings).

댓글을 달려면 로그인하십시오.

답변 (2개)

Image Analyst
Image Analyst 2015년 2월 15일
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
Guillaume
Guillaume 2015년 2월 15일
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
Kayuri Shah 2015년 2월 16일
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.

카테고리

Help CenterFile Exchange에서 String에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by