How do I display all values on one line using disp function only when values are taken from a loop
6 次查看(过去 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!