How to save an fprintf command to a variable?
76 次查看(过去 30 天)
显示 更早的评论
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 个评论
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
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
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
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!