MATLAB Answers


sprintf or disp

Asked by AP
on 17 Jun 2011

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])


sprintf('this is a test number: %d', 12)




No products are associated with this question.

3 Answers

Answer by Robert Cumming
on 17 Jun 2011

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.


Answer by Walter Roberson
on 17 Jun 2011

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.


on 17 Jun 2011

Could you elaborate on handling objects? Thanks.

For example, you can disp() a structure or a cell array, but sprintf() has no built-in ways to handle those.

Also note you can get rid of the "ans =" if you use fprintf() instead of sprintf() .

Answer by Krishna Kumar
on 17 Jun 2011

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


Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!