sprintf or disp

조회 수: 158 (최근 30일)
AP
AP 2011년 6월 17일
I have a question on the application and performance of disp and sprintf. Which one is recommended? For example, what is the difference between the following?
disp(['this is a test number: ' 12])
and
sprintf('this is a test number: %d', 12)

답변 (3개)

Krishna Kumar
Krishna Kumar 2011년 6월 17일
disp displays the string or variable in the command windoe, whereas sprintf can be used to output the result into a variable, GUI ,file etc

Robert Cumming
Robert Cumming 2011년 6월 17일
As well as being more flexible, sprintf is also much faster than disp when joining strings together like you have shown.
for writing to the command window I normally use fprintf. This also allows you to write your own error/warning/information messages:
fprintf ( 2, 'my error(warning) message in RED!\n' );
The number 2 signifies that you want to write to the command window in red font.

Walter Roberson
Walter Roberson 2011년 6월 17일
The first of the two prints out the quoted string followed by a newline (character 12).
The second of the two prints out
ans =
this is a test number: 12
sprintf() is much more flexible for formatting numbers and strings, but is not able to handle objects.
  댓글 수: 3
Walter Roberson
Walter Roberson 2011년 6월 17일
For example, you can disp() a structure or a cell array, but sprintf() has no built-in ways to handle those.
Walter Roberson
Walter Roberson 2011년 6월 17일
Also note you can get rid of the "ans =" if you use fprintf() instead of sprintf() .

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by