How would my script to show this in the command window?

My function is [s,m]=collatz(X). If I want s to equal the number of steps it takes for the number to equal one then how would I set it up? I know the idea is that the number of steps (s) increases by one every time the number goes through the while-loop. Then I need m to equal the maxvalue which comes from the biggest value in the list. Ex: >>[s,m]=collatz(3) s=7 m=16 since the list is 3-10-5-16-8-4-2-1
function[s,m]=collatz(x)
%This function will show the steps and maxvalue of even and odd natural
%numbers.It will show the show the number of steps it can repeat as long as
%the number is greater than one. It will show the maxvalue in the list
%Even numbers will be divided by 2
%Odd numbers will be multiplied by 3 and add to by one
%both will run as long as the result is greater than 1
clc
s=
m=
while x>1
if mod(x,2)==0 %shows x(natural number is even)
x=x/2
elseif mod(x,2)==1 %shows x(natural number is odd)
x=x*3+1
end
end

 Risposta accettata

Michael,
Initially, set s to be zero because no loop has been executed yet. Set m to be the same as x.
Inside the loop, s is increased by 1 after every iteration of the while-loop, like s=s+1. Set m to be equal to x if x is greater than m.

1 Commento

michael story
michael story il 26 Set 2018
Modificato: michael story il 26 Set 2018
This is what my professor sent and I figured out s but m is not working. I am also confused on what he means about my input value x in a function. Sorry if the picture is blurry or not rotated.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by