How to fix my function script?
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
michael story
el 26 de Sept. de 2018
Comentada: michael story
el 26 de Sept. de 2018
this is edited my script:
function[s,m]=collatz()
%This function will show the steps and maxvalue of even and odd natural
%numbers. It will show the number of steps needed for the number num to
%reach 1. 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=0
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
s=s+1;
m=max(?)?
The script above is what I understood from my professor's comments, but I am still lost the m(maxvalue) and what he is saying about my x value. Sorry if the picture is blurry or sideways.

0 comentarios
Respuesta aceptada
James Tursa
el 26 de Sept. de 2018
Editada: James Tursa
el 26 de Sept. de 2018
You need to have the step increment and the max calculation inside your while loop.
m = x; <-- Use this to initialize up front prior to the while loop
s = s + 1; <-- Put this inside your while loop
m = max(m,x); <-- Put this inside your while loop after the "if" block
4 comentarios
James Tursa
el 26 de Sept. de 2018
My guess is you pushed the green triangle button in the editor to run this function. That will run the code without defining the input n. You need to call this from the command line like this:
n = 5; % or whatever
[s,m] = collatz(n)
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!