How do I display all values on one line using disp function only when values are taken from a loop
7 ビュー (過去 30 日間)
古いコメントを表示
This is my code,
% Enter a number to test the Hailstone problem
number = input('Please enter a number: ');
% Enter loop, and remain
% in loop until the final
% number reaches value 1
n = 1;
while number > n
m = mod(number,2);
if m == 0
number = number / 2;
else number = (number * 3) + 1;
end
for result = number
disp(result);
end
end
Above is what I have entered, the result is below:
(note: these appear to be on one line but are not)
Please enter a number: 22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
However, I would like the results to be on one line, strictly adhering to the disp function. I have to create a variable called results and display it as an array. The results must have all the values and not just the final value. How do I achieve this?
Please enter a number: 22
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
0 件のコメント
回答 (2 件)
Matt Kindig
2012 年 4 月 24 日
The 'disp' function will automatically format each result onto a new line. Use the 'fprintf' function instead:
fprintf('%d ', result);
0 件のコメント
Walter Roberson
2012 年 4 月 24 日
Before the loop,
result = [];
Then replace
for result = number
disp(result);
end
with
result(end+1) = number;
And after the "while" loop,
disp(result);
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!