I would like to ask if there is a way to output a number, which is stored as a variable, using simple commands, as shown in the following examples:
9 is converted to: 'The number is +9.'
6.54 is converted to: 'The number is +6.54.'
-7 is converted to: 'The number is -7.'
-9.2 is converted to: 'The number is -9.2.'
0 is converted to: 'The number is 0.'
I would like to display it in the command window and a message box (msgbox).
Please help. Thanks in advance.

1 件のコメント

Alex Mcaulley
Alex Mcaulley 2019 年 4 月 10 日
What about str2double?

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

 採用された回答

madhan ravi
madhan ravi 2019 年 4 月 10 日
編集済み: madhan ravi 2019 年 4 月 10 日

0 投票

number = 10; % an example
if number>=0
sprintf('The number is : +%d',number)
else
sprintf('The number is : %d',number)
end
Assign a variable to sprintf() and then place it inside the command msgbox().

5 件のコメント

Angus Wong
Angus Wong 2019 年 4 月 10 日
編集済み: Angus Wong 2019 年 4 月 10 日
Sorry, what is %d? Why it isn't %g?
madhan ravi
madhan ravi 2019 年 4 月 10 日
Angus Wong
Angus Wong 2019 年 4 月 10 日
編集済み: Angus Wong 2019 年 4 月 10 日
If I want to display more than one numbers, such as:
a=9,b=8,c=0,d=-5,e=-6 (Not necceaasry in descending order.)
'The numbers are +9,+8, 0, -5 and -6 respectively.'
I have tried to do this, but its very long winded, and if there are 10 of them, it would get to thousands of lines. Any suggestions?
Guillaume
Guillaume 2019 年 4 月 10 日
Well, the first problem is that you use a different variable for each number instead of putting them all into a single array.
If the numbers were stored in a single array, your question is trivially solved in many ways. One way:
numbers = [9, 8, 0, -5, -6];
fprintf('The numbers are %s respectively.\n', strjoin(compose('%+d', numbers), ', '));
madhan ravi
madhan ravi 2019 年 4 月 10 日
編集済み: madhan ravi 2019 年 4 月 10 日
Thank you Guillaume, Stephen’s solution looks good but anyways let me give my suggestion too, use logical indexing group according to positive and negative numbers and use sprintf() all at once.

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

その他の回答 (1 件)

Stephen23
Stephen23 2019 年 4 月 10 日
編集済み: Stephen23 2019 年 4 月 10 日

0 投票

>> V = [9,8,0,-5,-6]; % your data should be in one array.
>> S = sprintf(', %+g',V(1:end-1));
>> S = sprintf('The numbers are%s and %+g respectively',S(2:end),V(end))
S = 'The numbers are +9, +8, +0, -5 and -6 respectively'
˜>> regexprep(S,'\+0([, ])','0$1') % if you don't like '+0'
ans = 'The numbers are +9, +8, 0, -5 and -6 respectively'

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

製品

リリース

R2019a

質問済み:

2019 年 4 月 10 日

編集済み:

2019 年 4 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by