Notes On Algorithms And Control Structures Part B

Notes Partbpdfalgorithms And Control Structures Part Bthis Week We W

Notes Partbpdfalgorithms And Control Structures Part Bthis Week We W notes-partB.pdf Algorithms and control structures: part b This week we will continue to learn about conditional structures. Namely: while loops and nested conditional statements. The portfolio tasks this week will include both content from this week's workshop and last week's workshop. While Loops A while loop will operate the same as a for loop, except it will continue to loop while a certain condition is met, rather than having a set number of loop iterations. While loops don't automatically have a counter like for loops, so you might need to code one as part of the process if required. While loops will iterate forever if the condition is always met, so it is important to have safeguards in place in case this issue arises. Ctrl + c will stop any script from running, and an if statement could be used to stop the script if the number of iterations exceeds a certain amount by using a break command. Example 1: Square Number DIsplay This code displays square numbers while they are below the input N. N = 100; %input i = 1; %counter while i^2 = A error('already have enough saved') end i = 0; %counter while B B; i = i + 1; %counter increases by 1 each iteration end disp(i) %output Activities For each of the following activities, write an algorithm for the process, then write some code that runs the algorithm. 1. A process that counts to a certain number, N. % write your code here 2. A process that sums up all the even numbers until the sum surpasses N. % write your code here 3. A process that stores all the powers of two that are less than N in a vector. % write your code here Nested control structures It shouldn't be a surprise that control structures can be combined. A nested control structure is when one control structure is included inside another. For example, an if statement can be placed inside a for loop, a for loop can be nested inside another for loop or a while loop. Nested For Loops Nested for loops occur when there is a for loop within a for loop. These can be useful when you have a repetitive task where you would like to vary multiple inputs simultaneously. The example below performs the operation Ax, where A is a matrix and x is a vector. It assumes MATLAB can perform scalar operations, but not matrix operations (which of course isn't true, but it makes for a simple introduction to nested loops!). A = [1 2;3 4;5 6]; b = [7;8]; [rows,columns] = size(A); 2 MatrixMultiply = zeros(rows,1); for i = 1:rows for j = 1:columns MatrixMultiply(i) = MatrixMultiply(i) + A(i,j)b(j); end end disp(MatrixMultiply) Activities 1. Write a for loop that finds the maximum number in a vector, that will work for a vector of any length. Hint: you will need an if statement somewhere. % Insert code here 2. Write a for loop that finds the maximum number in a matrix of any size. Hint: you will need nested for loops and an if statement. % Insert code here 3. Write an algorithm, and then some code that searches a matrix for the first column that has a vector- magnitude greater than a value N. A test matrix is provided below. If there is no column that has a magnitude greater than N, the code should produce an error message. A = [5,5,4;4,5,4;1,4,2] N = 5. %insert code here Portfolio 3 part b Submission instructions 1. Questions 1 and 3 of this portfolio should be submitted as a single pdf file titled n#######Portfolio3.pdf (including that from portfolio 3 part a). Question 2 must be submitted as a .m file titled n########Portfolio3b.m. 2. Clearly indicate what part of the portfolio you are answering. 3. The assignment is DUE at 11:59pm Monday 14th May and should be submitted through Blackboard. The IT helpdesk closes at 10pm, and so if you leave your submission to the last minute and something happens then you may not be able to received any assistance. Late submissions will recieve a mark of zero. Taylor series 3 The taylor series is a special series that approximates complicated functions as a polynomial. It is given by where is the derivative of evaluated at a. To create the approximation, we truncate the series at some maximum term Nto give The Taylor series is used in many scenarios, including when certain mathematical methods may not applicable (such as integration). Or for creating the finite difference approximations, as seen in the week 7 worksheet. 1) Write an algorithm for computing a taylor series to N term. 2) Write a MATLAB function that accepts three inputs (FUN, a, N), where FUN is an annonymous function, a is the point the taylor series is centered around and N is the order of the taylor series. The MATLAB function should output the Nth order Taylor series for the function about a. You are not permitted to use the taylor function in MATLAB to solve the problem. 3) Apply the function to solve the 10th order Taylor series of about hint: if you choose to test your function, you can compare it to the output from wolframalpha here. 4 notes-partC.pdf Numerical Methods So far throughout this unit, we have spent several weeks learning how to solve ODEs analytically. There are many ODEs, however, that do not have an analytical solution. For these ODEs, we rely on numerical methods to come up with an approximate solution. For these ODEs, we rely on MATLAB's in-built ODE solvers, ode45. In addition to this, we will explore how to write your own ODE solver. Solving a Single ODE with ode45 The ode45 function requires three inputs and has two outputs, as shown below. The first input, , represents the equation for y'. It must be represented in the form of a function, which can be done through an anonymous function, or with a separate function file. In this worksheet, we will use anonymous functions. The format for an anonymous function is . The second input, , is a vector that contains the start time and end time of the simulation: . The third input, , represents the value for y at the start time. The outputs, and , are vectors of t and y values. Numerical methods only provide co- ordinates of the solution rather than an equation. In order to view the solution you should plot it. Example: Solve ODEFUN = @(t,y) 2y/t - 2yt; TSPAN = [1 10]; Y0 = 5; [TOUT,YOUT] = ode45(ODEFUN,TSPAN,Y0); plot(TOUT,YOUT) Try solving the following ODEs using ode45. 1. % Insert code here 2. % Insert code here . % Insert code here Solving Systems of ODEs using ode45 If the system your are solving for is a higher order ODE, or can't be fully described as a single ODE, then we must solve by treating it as a system of ODEs. Solving a system of ODEs using ode45 is the same as what we saw previously, except the inputs are now vectors. The first input, , is now a column vector containing equations for y'. We now write it in the form . The input vairable y is a column vector as well, and so to access the individual dependent variables, we call their location in the y vector: y(1) and y(2). The second input, , is unchanged form what we saw previously. The third input, , is now a column vector containing the initial values for all the variables. is still a vector containing t values, but is now a matrix containing y values, where each column is a different solution vector. Example: ODEFUN = @(t,y) [y(2)-y(1);2y(1)-y(2)]; TSPAN = [0 5]; Y0 = [1;0.5]; [TOUT,YOUT] = ode45(ODEFUN,TSPAN,Y0); plot(TOUT,YOUT) legend('y_1','y_2') Now try the following examples. 1. % Insert code here 2. % Insert code here . % Insert code here . % Insert code here Writing Your Own ODE Solver When MATLAB is readily available, using will be the simplest and most accurate way to numerically solve ODEs. However, if MATLAB is unavailable, it becomes important to understand how to write your own ODE solver. This will also give you some more practice with writing algorithms. In last week's lecture, we went through three common numerical methods for solving ODEs, which were Euler's method, modified Euler's method, and Runge-Kutta (RK4). We saw how to code the Euler method and modified Euler method in class and now you will implement the RK4 method. RK4 Method: the RK4 method, just like Euler's method, solves first order ODEs in the form . The method solves the ODE by evaluating the following equations. Where the k values are defined through the following equations: We can see that the RK4 method will require four inputs. The first three are the same as ode45, in that we need to know the ODE we are solving, the time span and the initial condition. The fourth input required will be the step size, h. We would like for the function to create two outputs, TOUT and YOUT. The process of applying RK4 is iterative, meaning we should be able to describe it in MATLAB using a for loop or a while loop. Now try and write the following numerical solvers. 1. Write an algorithm for the RK4 method. 2. Convert the algorithm to code that computes the RK4 method. You can submit your code on AMS (practice activities) to check that it's correct. 3. Solve the ODE using your RK4 function, given , , y(0) = 1. 4. Compare your solution to the Euler, modified Euler, and ode45 solutions (these are all available to download from the week 8 lecture files (example1.m, example2.m, example3.m). 5. Bonus (time permitting): experiment with the accuracy of each method as the step size is changed. Try seeing if you can do this using a for loop. 3 Portfolio 3 Part C - competing species In Central Queensland, cattle farmer Sam is trying to grow sufficient grass for his cattle to feed on. However, as his grass grows, the kangaroos start to gather and eat Sam's grass! However, as his grass grows, the kangaroos start to gather and eat Sam's grass! To combat this, Sam plants additional grass on his land that, in turn, attracts even more kangaroos. To understand the dynamic of these competing species (the grass (g(t)) and kangaroos (k(t)), we can use the following system of ODEs. where and are growth constants. 1) Write out explicitly the matrix-vector representation of this system. Clearly define the elements 2) Write an algorithm describing how this would be implemented to solve for given h, , and as inputs. 3) Implement this algorithm in MATLAB to solve for given and you can assume that initially there are no Kangaroos and 1083ha of consumable grass available. 4) Plot the solutions (in an appropriate manner). Explain why this model is or isn't appropriate (is there a point where it becomes unrealistic?) parts-portfolio.docx notes-partA.pdf algorithms and control structures: part a this week we will introduce algorithm development and two control structures: if statements and for loops. Next week, you will be introduced to while loops and nested conditional statements. The portfolio tasks will be combined into a single week. Algorithms One of the hardest transitions to make when first learning to program is how to 'think like a computer'. Computers can do simple tasks extremely fast, but must, at some point, be given specific instructions on what to do. A computer performs all of its tasks through the application of an algorithm. An algorithm is a set of instructions that can be performed one by one. They are as basic as possible (although can add together to produce complex behaviour). Each step in an algorithm should be irreducible enough to remove any 'open' interpretation - that is, given the same inputs, the same result should be obtained. In general, when writing an algorithm, it is a good idea to provide four key parts: Input, Setup, Process, and Output. In additional to this, the algorithm needs to terminate. Input: should contain all values given to the algorithm by a user, except where prompts for values are included in the algorithm process. Setup: involves arranging the initial state of the system, such as initialising a sum variable to zero. Process: is the essential part of the algorithm, describing how the output is obtained. Output: should list things that specifically are given by the algorithm, the set of results that you should obtain when following the algorithm. Terminate: Finally, all Algorithms must come to an end. Activity 1 Imagine that you have access to a "human computer''. This HC is capable of taking instructions in English (so long as the instructions are simple ones that are clear and concise), and can perform basic human actions, such as "put on shirt''. The HC understands concepts such as closeness, temperature, time, and the various weather conditions. 1. Working alone, write an algorithm for the process of getting dressed in the morning. 2. Compare your algorithm to other members in your group. How different are they? Is there any room for interpretation? From Algorithm to Program There are three forms that we could write instructions in. Algorithm: is a series of instructions in human language, providing a clear and concise way for a human to read and understand the process involved. Algorithms are often written to suit the level of the human that is expected to read it, and thus may include complex instructions that it is assumed the reader knows, such as "obtain the roots of the quadratic''. Pseudocode: is a set of instructions written in a generic language. That is, it is written to still be easily followed by a human, but is formatted like most programming languages. It often uses simple human instructions such as "Set x=2'', "Repeat Until x>5'', or "Stop When err 5 x = x + 2 end Example 2: Elseif statement x = 1; if x == 10 x = 0; elseif x > 4 x = x + 2 end Example 3: Else statement x = 1; if x >= 5 x = x + 2 else error('number is less than 5') end Activities 1. Write an if statement that dispays the value of a variable (x) if the value is less than or equal to zero. % Write your code here 2. Write an algorithm that finds the larger of two numbers (a,b). Consider positives to always be larger than negatives (Eg. 3 is larger than -5, -1 is larger than -4). Convert this to a MATLAB function called max2. % Write your code here 3. Write an algorithm that finds the largest of the four numbers (a, b, c, d). Convert this to a MATLAB function called max4. hint: you do not need to check every single combination % Write your code here 4. Alter the previous code so that it counts the number of times the maximum number appears. % Write your code here Programming: For Loops A 'for' loop repeats a process a set number of times, but changes one variable (called the counter) each time. They are particularly useful when dealing with any repepitive process. The range of values that the counter takes on is given at the start of the for loop. Run the examples below to see how for loops work. Example 1: Basic For Loop The following for loop displays the whole numbers from 1 to 10. for i = 1:10 disp(i) end Example 2: Triangular Numbers The following for loop determines the Nth triangular number. N = 10; %input triangular = 0; %setup - initial value required for i = 1:N triangular = triangular + i end disp(triangular) %output Example 3: Triangular Numbers with Storage The following for loop stores all the triangular numbers up to the Nth number within a vector. N = 10; %input triangular(1) = 1; %setup - initial value required for i = 2:N triangular(i) = triangular(i-1) + i end disp(triangular) %output Activities 1. Write a