How do I display all values on one line using disp function only when values are taken from a loop

9 views (last 30 days)
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

Answers (2)

Matt Kindig
Matt Kindig on 24 Apr 2012
The 'disp' function will automatically format each result onto a new line. Use the 'fprintf' function instead:
fprintf('%d ', result);

Walter Roberson
Walter Roberson on 24 Apr 2012
Before the loop,
result = [];
Then replace
for result = number
disp(result);
end
with
result(end+1) = number;
And after the "while" loop,
disp(result);
  1 Comment
Mohammad Dalati
Mohammad Dalati on 24 Apr 2012
Just noticed another bug, the 22 (first number) isn't being displayed when it should be. A boolean expression is being carried out on the number before it can be displayed. How do I fix that?

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!