MATLAB Answers

How to display two things on one line?

279 views (last 30 days)
Cole Bromfield
Cole Bromfield on 15 Jan 2020
Edited: per isakson on 16 Jan 2020
My assignmend is telling me to use the display command to display the phrase "The first random variable is" and the x value (calculated earlier in the script) on the same line. The result should be:
The first random variable is 4
Not:
The first random variable is
4
Heres the code (don't worry about the y value)
x=ceil(5*rand(1));
y=floor(99*rand(1));
disp("The first number is ")
disp(x)

  2 Comments

per isakson
per isakson on 15 Jan 2020
Homework I assume.
You have to do it with one disp() statement, because disp() automatically adds a newline after the output
Image Analyst
Image Analyst on 15 Jan 2020
Or use fprintf() like I show in my Answer below.

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 15 Jan 2020
Use fprintf():
fprintf('The first random variable is %d.\n', x);

  0 Comments

Sign in to comment.


per isakson
per isakson on 15 Jan 2020
Edited: per isakson on 16 Jan 2020
See Append Text to Strings before you try my code.
>> "abc"+"def"
ans =
"abcdef"
>>
and your example
>> x = 17;
>> disp( "The first number is " + num2str(x) )
The first number is 17
it's even possible to add the numerical x to the string.
>> disp("The first number is " + x )
The first number is 17
The doc on plus, + Addition says
If one input is a string array, then the other input can be a numeric, logical, character, string, or cell array.
>> "true is displayed as "+true
ans =
"true is displayed as true"

  0 Comments

Sign in to comment.

Sign in to answer this question.

Tags