display while loop output as an array

2 Ansichten (letzte 30 Tage)
Ahmed Emam
Ahmed Emam am 5 Okt. 2017
Kommentiert: Walter Roberson am 5 Okt. 2017
how do you display the output of a while loop as an array.
code:
function [] = hailstone_sequence(n)
n = input('Value for n: ');
h = 1;
while(n~=1)
if n==1
return
elseif mod(n,2)
n=3*n +1
else
n=n/2
end
h=h+1;
end
  2 Kommentare
jean claude
jean claude am 5 Okt. 2017
what's your output variable ?
Ahmed Emam
Ahmed Emam am 5 Okt. 2017
the output should be the values for each iteration in an array, so for 3 the output should be 3 10 5 16 8 4 2 1

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 5 Okt. 2017
Just before the h=h+1 insert
output(h) = n;
  2 Kommentare
Ahmed Emam
Ahmed Emam am 5 Okt. 2017
tried it, works but I am missing the initial value
Walter Roberson
Walter Roberson am 5 Okt. 2017
Then move it to after the while() statement.
But question: does the output need to include the 1? If so then make sure to add a 1 to the end before the return statement.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

jean claude
jean claude am 5 Okt. 2017
Bearbeitet: jean claude am 5 Okt. 2017
function [output] = hailstone_sequence(n)
output=[n];
h = 1;
while(n~=1)
if n==1
return
elseif mod(n,2)
n=3*n +1
else
n=n/2
end
h=h+1;
output= [output n];
end

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by