Question about disp([]) and returning lines

39 views (last 30 days)
Josh Chiu
Josh Chiu on 14 Feb 2015
Answered: dpb on 14 Feb 2015
In a recent HW assignment I had to output a mixed array of strings and variables using disp. I didn't have any problem formatting the text of my output, but when the code was exported to pdf the output (which also gets displayed in command window) got cut off. I tried to figure out if it was possible to use
\n
to return the line. In the end, I had to use two different disp commands so that the text would go on two lines and not get cut off the page:
disp(['For a barbell composed of two spheres (r = '...
num2str(sphererad) 'cm) connected by a bar' ])
disp(['(l = ' num2str(rodlength) ...
'cm, d = ' num2str(roddiam) 'cm), the'...
' volume is ' num2str(barbellvol) ' cubic cm.']);
Which output
For a barbell composed of two spheres (r = 7cm) connected by a bar
(l = 10cm, d = 1cm), the volume is 2881.3641 cubic cm.

Answers (3)

John D'Errico
John D'Errico on 14 Feb 2015
No. You cannot use disp to finely control the output as it appears you wish. \n will not work with disp.
You can use fprintf though.

Geoff Hayes
Geoff Hayes on 14 Feb 2015
Josh - according to disp, you may be able to create the string that you want to display (with carriage returns) before passing it to the function. We would use sprintf to build the string as
sphererad = 7;
rodlength = 10;
roddiam = 1;
barbellvol = 2881.3641;
myString = sprintf('For a barbell composed of two spheres (r = %f cm) connected by a bar\n(l = %f cm, d = %f cm), the volume is %f cubic cm.\n', sphererad, rodlength, roddiam, barbellvol);
Then passing myString into disp we get
disp(myString)
For a barbell composed of two spheres (r = 7.000000 cm) connected by a bar
(l = 10.000000 cm, d = 1.000000 cm), the volume is 2881.364100 cubic cm.
which may be closer to what you want.

dpb
dpb on 14 Feb 2015
disp is for when you don't really care about the formatting but just simpler output; it doesn't accept any formatting instruction. Also, as you realize, to mix character and numeric values you have to convert to string manually.
fprintf(['For a barbell composed of two spheres (r = %.2f cm) connected by a bar\n'...
'(l = %.2f cm, d = %.2f cm), the volume is %.4f cubic cm.'], ...
sphererad,rodlength,roddiam,barbellvol)
I think I got the quotes, brackets and paren's balanced... :)
Or you can write the above to a string via sprintf and use disp to show it if want to keep local copy. Or, another slight perturbation is to write a separate formatting string outside the f|sprintf call...

Community Treasure Hunt

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

Start Hunting!