Final Exam Review

Created

MATLAB

Create a function:

function [y1, y2] = name(x1, x2, x3)

Anonymous Functions:

y = @(x,z) 3*x + 6*z

Open files

% opens as write only
 fileID = fopen(filename, 'w');

% write to file
fprintf(fileID, '%.6f %.6f\n', x(i), y(i));
   
% close file
fclose(fileID);

Random

rand(1)

Generates a random decimal number between 0 and 1.

Graphing

2D Plotting If x and y are a vectors of values:

plot(x,y)

Using linspace and an equation:

x = linspace(1,10,100);
y = (2./x).^3;
plot(x,y,'go-') % green, circle marker, solid line

3D Plotting

plot3(x,y,z)

Plotting area

xlim(lower_bound, upper_bound);

Labling Use hold on to add stuff to the same figure.

% add a title
title('title');

% label axis
xlabel('x');
ylabel('y');
zlabel('z');

% add text
text(x,y,'text');

Euler's Method:

Given

  1. first order ordinary differential equation: dydx\frac{dy}{dx} as dxdt
  2. initial condition y0=y(x0)y_0 = y (x_0)

We determine yi=y(x0+ih)y_i = y(x_0 + ih) for i=1,2,...i = 1,2,... by using Euler's Method. y0=y(x0)y_0 = y(x_0) yi+1=yi+h∗f˙(xi,xy)y_{i+1}=y_i+h* \dot f(x_i,x_y) for i=1,2,...i=1,2,...

for i = 1:max_steps
    y(i+1) = y(i) + dydt(t(i), y(i))*(h);
end

Runge-Kutta Method

These methods acheive the accurracy of the taylor series approach without requiring the calculations of higher derivatives.

yi+1=yi+ψ(xi,yi,h)hy_{i+1} = y_i + \psi (x_i,y_i,h)h ψ=a1k1+a2k2+...+ankn\psi = a_1 k_1 + a_2 k_2 + ... + a_n k_n <-- Increment Function

aa's are constants

k1=f(xi,yi)k_1 = f(x_i, y_i) k2=f(xi+pih,yi+q11k1h)k_2 = f(x_i + p_i h, y_i + q_{11} k_1 h) <-- pp's and qq's are constants k3=f(xi+p3h,yi+q21k2h+q22k2h)k_3 = f(x_i + p_3 h, y_i + q_{21} k_2 h + q_{22} k_2 h) ... kn=f(xi+pn−1h,yi+qn−1k1h+qn−1,2k2h+...+qn−1,n−1kn−1h)k_n = f(x_i + p_{n-1} h, y_i + q_{n-1} k_1 h + q_{n-1,2} k_2 h + ... + q_{n-1,n-1} k_{n-1} h)

The order is chosen as nn and the values of a, p, q are evalulated by setting the general equation equal to terms in a Taylor series expansion.

Fourth Order Runge Kutta (RK4): K1=f(xi,yi)K_1 = f(x_i, y_i) K2=f(xi+1/2h,yi+1/2k1h)K_2 = f(x_i + 1/2h, y_i + 1/2 k_1 h) K3=f(xi+1/2h,yi+1/2K2h)K_3 = f(x_i + 1/2 h, y_i + 1/2 K_2 h) K4=f(xi+h,yi+K3h)K_4 = f(x_i + h, y_i + K_3 h) yi+1=yi+h6(K1+2K2+2K3+K4)y_{i+1} = y_i + \frac{h}{6} (K_1 + 2K_2 + 2 K_3 + K_4)

You need the following input

  • dydt the name of the M-file that evalues that ODE
  • tspan consisting of ti and tf that corresponds to the initial and final times.
  • y0 is the initial values of the dependent variable
  • h is the stetpsize

Before we start:

  1. check that nargin >= 4 (if you are accepting optional inputs)
  2. check that tspan is span some time
  3. populate the independent vector (create time t)

The computation:

for i=1:(length(x)-1) % calculation loop
   k1 = dydt(x(i),y(i));
   k2 = dydt(x(i)+0.5*h,y(i)+0.5*h*k1);
   k3 = dydt((x(i)+0.5*h),(y(i)+0.5*h*k2));
   k4 = dydt((x(i)+h),(y(i)+k3*h));
   
   y(i+1) = y(i) + (1/6)*(k1+2*k2+2*k3+k4)*h; % main equation
end

Solving system of equations

If A is the matrix and B is the column of solutions. Solve with one of the following ways

% inverse 
x = inv(A)*b

% rref
r = rref([a b]);
x = r(:, 4);

Solve an equation

syms x
eqn = sin(x) == x^2 - 1;
S = solve(eqn,x)

Polynomials

Fit a set of points to a polynomial with n degrees with polyfit:

p = polyfit(x,y,1)

p contains two coefficients that describe a linear curve fit.

Use polyval to evaluate the a polynomial at the given points

p = polyfit(x,y,1);
x = [25 30 35 40 45];
y = polyfit(p, x);

Mean Squared Error (MSE)

Matlab function: err = immse(x,y).

Doing it manually: MSE=1n∗Σ(actual−forcast)2MSE = \frac{1}{n} * \Sigma (actual-forcast)^2

  • where n is sample size

Newton's Method

Approximates the real zeros of a function by using tangent lines to approximate the graph of the functions near its x-intercepts.

Consider function f that is continuous and differentiable on the interval [a b]. Choose a starting point x1.

The equation of the tangent line is y=f′(x1)(x−x1)+f(x1)y = f'(x_1) (x-x_1) + f(x_1)

If we let y=0y=0 and solve for xx we find the new estimate: x=x1−f(x1)f′(x1)x = x_1 - \frac{f(x_1)}{f'(x_1)}

We can improve on the value by calculating another estimate using the old estimate x2=x1−f(x1)f′(x1)x_2 = x_1 - \frac{f(x_1)}{f'(x_1)}

Generally: xn+1=xn−f(xn)f′(xn)x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}

The code look something like

function [xr, iter, err, results] = newtons_method(f, fder, xi, iter_max, tol) 
    xr = xi;
    for iter=1:iter_max
        xrold = xr;
        xr = newtons_update(f, fder, xrold);
        err(iter) = abs((xrold - xr)/xrold);
        results(iter) = xr;
        if (err(iter) < tol) 
            break;
        end
    end
end

where newtons_update is:

function [xr] = newtons_update(f,fder, xi)
    xr = xi - f(xi)/fder(xi);
end

Least Squares Approximation

Do it with matlab's built in function: polyfit.

It's goal is to minimize error betweent the fit line and the data poins. Minimize{Error=Σ[yi−(axi+b)]2} Minimize\{Error = \Sigma [y_i - (ax_i + b)]^2\}

  • Error can also be written as Σ[yi−f(xi)]2\Sigma [y_i - f(x_i)]^2

Taking the derivative of this to minimize involves quite a bit of work... refer to lab10

Reading Input

Use fopen to open the file. Use fscapf(fileID, '%f') to read numbers

  • or use %c to read as strings

You can choose a whole line with tline = fgetl(fileID) and iterate through the whole file until it reaches the end. Here is an example of reading and displaying each line of a text file:

fid = fopen('badpoem.txt');

while ~feof(fid)
	tline = fgetl(fid);
	disp(tline)
end

fclose(fid);