How to display two things on one line?

504 ビュー (過去 30 日間)
Cole Bromfield
Cole Bromfield 2020 年 1 月 15 日
編集済み: Paul 2023 年 3 月 3 日
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 件のコメント
per isakson
per isakson 2020 年 1 月 15 日
編集済み: per isakson 2020 年 1 月 15 日
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 2020 年 1 月 15 日
Or use fprintf() like I show in my Answer below.

サインインしてコメントする。

採用された回答

Image Analyst
Image Analyst 2020 年 1 月 15 日
Use fprintf():
fprintf('The first random variable is %d.\n', x);
  1 件のコメント
Noah Brühwiler
Noah Brühwiler 2022 年 11 月 17 日
so ein müll

サインインしてコメントする。

その他の回答 (2 件)

per isakson
per isakson 2020 年 1 月 15 日
編集済み: per isakson 2020 年 1 月 16 日
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"

Paul
Paul 2023 年 3 月 3 日
Would this be considered a character array or string? I need to output text without using either...
disp("The original number was "+integer+" and the flipped number is "+flipped)
  3 件のコメント
Walter Roberson
Walter Roberson 2023 年 3 月 3 日
If the point is that the output must not have the quotation marks, then disp() should work for that purpose.
But I suspect that the restriction is hinting that you should be using fprintf.
Paul
Paul 2023 年 3 月 3 日
編集済み: Paul 2023 年 3 月 3 日
This image is from the assignment. Yeah, it seems weird to me too. But I also may not be understanding what it means fully.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLarge Files and Big Data についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by