<< Return to class page

Math 151 Lab 04 - 01/29/2018:

DUE: Wednesday, 31, 2018 (by 4:00pm before class starts)

INSTRUCTIONS: Save this Matlab script with the filename LastName_Lab04.m (example: Lewis_Lab04.m). Complete each question using MATLAB code. When you are ready to have your assignment graded, use the PUBLISH command to generate a pdf file, and submit the resulting file to CANVAS.

Please make sure to leave code uncommented unless I ask for a comment. You do not need to label your steps for each problem, but I should be able to see you do each step I asked for.




There is a famous algorithm called the "bubble sort" algorithm, which we're going to implement here. It will sort a vector until the entries are all in ascending order.

Step 1: Set x=[1,8,3,6,2,9,7,5,4]

Step 2: Use nested loops (i.e., two for loops) to sort x. The inner loop isn't bad: loop over elements of x from 1 to 8, and if x(j) > x(j+1), then swap them. You may need an extra variable to store one of the values while you swap them.

Step 3: Since you have suppressed the output within the loops, verify that your code sorted x so you have x=[1,2,3,4,5,6,7,8,9] (this means print x to the screen).




Write a function called "collatz" below where you take an input n, and if n is odd, return 3*n+1. If n is even, return n/2. (You need to compute mod(n,2) to test for even/odd. If mod(n,2)==1, n is odd, otherwise n is even.)

Note: You cannot use the keyword function when you publish. To avoid errors, paste your function code below as comments.




Please make sure your collatz function from the previous problem is correct first.

Step 1: Set up a list of 100 blank counters (i.e., c=zeros(1,100)) and a list of x values x=1:100.

Step 2: Use a while loop inside a for loop to reassign x(i) to the value collatz(x(i)), and every time it reassigns x(i), add 1 to counter c(i). (Hint: Your while loop should run as long as x(i) is not equal to 1, and your for loop should loop over all entries of x). What you are checking is how many times you have to apply the collatz function in order for x to reach 1 given different initial conditions.




Plot your list of counters from #3 as a scatter plot of x (the integers from 1 to 100) vs. c. Instead of using the markers Matlab gave you, please plot the points as red diamonds when you use the scatter or plot commands. Label your vertical and horizontal axes and give the plot a title (These can be whatever you wish. I just want to see that you know how to set them.)


Does there seem to be any pattern to the number of tries and the x-value or does it seem to be completely random?