The document discusses loops in MATLAB, which allow repeated computations on different numeric values without writing multiple lines of code. It provides examples of for loops to compute values in a vector or matrix based on an incrementing index variable. Nested loops are also demonstrated, where one loop is contained within another. Tasks are assigned for readers to write MATLAB functions using for loops to cube values in a vector, compute savings growth over time with interest and bonuses, and plot the results.
3. Loops are essential Code allows repeated numerical computations. We do not want to write line of code 10 times to do the same thing with different numbers. We want to tell the computer to use the same line, but with different numbers. Look at the example on next page.
4. week2_loops_essential.m Open the file. Two ways to compute 6 values First look at lines 11-16 Or try lines 19-21 Now imagine you needed to do this for 100 different values, or a 1000. Using a loop is simple to code and efficient.
5. How does a loop work? for k=1:6; y2(k)=sin(xvalues(k)); end … more code First k=1 hence do y2(1)=sin(xvalues(1)); Back to start of loop Now k=2 hence do y2(2)=sin(xvalues(2)); Now k=3 hence do Y2(3)=sin(xvalues(3)); Now k=4 hence do y2(4)=sin(xvalues(4)); Now k=5 hence do y2(5)=sin(xvalues(5)); Now k=6 hence do y2(6)=sin(xvalues(6)); Now k=6 is equal to max of allowed k, continue to next line of code
6. How to write the statement k takes the values 3,4,5,6,7,8 for k=3:8 code end for k=8:-2:2 code end k takes the values 8,6,4,2 for k=4:3:13 code end k takes the values 4,7,10,13
7. General examples of for loops Open the file week2_for.m Note the call statement has 3 variables. Run in the command window Note values of k are: start, start+step, start+2*step,…,start+6*step
8. Nested loops Open week2_for2.m Note that one loop is inside another loop. First k=1 and then l goes from 1 to 5. First k=2 and then l goes from 1 to 5. …. Finally k=10 and then l goes from 1 to 5. Inner loop Outer loop Run the file and experiment with changing the loop for statements
9. TASKS Use help week2_loop_for_plotting.m and determine how to run this file and also how it works. Write a function file which takes as its input a vector of arbitrary length and then use a loop to define the output vector whose values are the cubes of the coefficients of the first vector plus one. The syntax could be: output_vector= week2_loop_cube(input_vector) Write a file to compute savings growth over time. For instance, let savings with an interest rate of 5% and annual bonus of £5 grow according to the model: Write a file with syntax Pounds=savings_growth(Pounds_in, interest_rate, annual_bonus,years_invested) The file should also plot savings growth.