display while loop output as an array
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Ahmed Emam
le 5 Oct 2017
Commenté : Walter Roberson
le 5 Oct 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 commentaires
Réponse acceptée
Walter Roberson
le 5 Oct 2017
Just before the h=h+1 insert
output(h) = n;
2 commentaires
Walter Roberson
le 5 Oct 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.
Plus de réponses (1)
jean claude
le 5 Oct 2017
Modifié(e) : jean claude
le 5 Oct 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
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!