How do I display all values on one line using disp function only when values are taken from a loop
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (2)
Matt Kindig
il 24 Apr 2012
The 'disp' function will automatically format each result onto a new line. Use the 'fprintf' function instead:
fprintf('%d ', result);
0 Commenti
Walter Roberson
il 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);
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!