Subject: Matlab (4 points) In HW#3, we created some code to play around with the
ID: 2257799 • Letter: S
Question
Subject: Matlab
(4 points) In HW#3, we created some code to play around with the Collatz conjecture. Put a copy of this code into your HW4 directory, and modify it so that it is a function file. It will take a positive integer as an input and will output the number of steps necessary for the Collatz process Look up the Collatz conjecture on the Wikipedia. There is a plot with red dots. Let's make that plot. Write a function that calls your function from part (a), runs through all integers from 1 to 10,000, and creates an array containing the number of steps required in order to reach 1. Use a plot (num,steps, 'o) command at the end to generate the plot. Turn in the plot. to converge to 1Explanation / Answer
(a) MATLAB function to calculate the number of steps for collatz sequence to converge to 1:
function nSteps = collatz(n)
%This function takes positive integer as an input and returns the number of
%steps it will take for the collatz sequence to converge to 1
nSteps = 0;
while n ~= 1
if mod(n,2) == 0
n = n/2;
nSteps = nSteps+1;
else
n = 3*n+1;
nSteps = nSteps+1;
end
end
(b) MATLAB script for the collatz plot:
for k = 1:10000
nSteps(k) = collatz(k);
end
plot(1:10000,nSteps,'o');