Introductory Programming Fall 2006 For today, you should have: 1) worked on the two exercises from notes04 Today: 0) splitting sections? 1) functions 2) eval 2 debriefing 3) update2.m For next time you should: 1) work on the exercise below 2) prepare for the next evaluation, which will cover vectors Evaluation 2 ------------ Here's the solution we looked at last time: xnew = x + sigma * (y - x) * dt ynew = y + (x * (r - z) - y) * dt znew = z + (x*y - b*z) * dt x = xnew y = ynew z = znew Here is the most common answer I saw on the evals: x(n+1) = x(n) + sigma * (y(n) - x(n)) * dt y(n+1) = y(n) + (x(n) * (r - z(n)) - y(n)) * dt z(n+1) = z(n) + (x(n)*y(n) - b*z(n)) * dt This is INCORRECT, because 1) the variable n is never initialized, and 2) x, y, and z are scalars, so trying to access the nth element will probably "exceed matrix dimensions" Remember, if you write something like x(n+1) = x(n) + ... you are reading and writing the elements of a matrix. It is very important to keep track of what is a scalar and what is a vector, so YOU MUST USE CAPITAL LETTERS FOR VECTORS. That way, when you use a vector, you will know that you are using a vector, and I will know that you know that you are using a vector. Here is a correct version of the program, using vectors and a loop. You can download it from wb/ip/code/lorenz_diff.m sigma = 10; b = 8/3; r = 28; dt = 0.01; X(1) = 1; Y(1) = 2; Z(1) = 3; for i = 1:1000 X(i+1) = X(i) + sigma * (Y(i) - X(i)) * dt; Y(i+1) = Y(i) + (X(i) * (r - Z(i)) - Y(i)) * dt; Z(i+1) = Z(i) + (X(i)*Y(i) - b*Z(i)) * dt; end plot3(X, Y, Z) Anybody know what this is? update.m -------- Let's look at another example; you can download it from wb/ip/code/update2.m n = 35; A(1) = 150; B(1) = 150; for i=1:n-1 fromA = round(0.03 * A(i)); fromB = round(0.05 * B(i)); A(i+1) = A(i) - fromA + fromB; B(i+1) = B(i) - fromB + fromA; end hold on plot(A, 'ro-') plot(B, 'bx-') Notice the before/during/after structure: 1) before the loop, initialize the parameters and the initial values of the vectors 2) inside the loop, add the next value to the vectors 3) after the loop, plot or return the accumulated result Exercise -------- Write a function named mysum that takes a vector as an input variable and that returns the sum of the elements in the vector. (It's called mysum because MATLAB already has a function named sum that does the same thing.) Your function should not print (display) anything, so when you call it, it should behave like this: >> X = 1:10; >> total = mysum(X); >> total total = 55