Lecture 2
-
Upload
koupable-up -
Category
Documents
-
view
214 -
download
1
Transcript of Lecture 2
Matlab Lecture 2
% inline functions
f = @(x) sin(x)-cos(x)+exp(-x)
f(0)
f([0,pi/4,pi/2,3*pi/4,pi])
% m files - scripts
who
timelinsolve
who
% m files - functions
clear
timelinsolvefun(1000)
who
[x1,x2]=timelinsolvefun2(1000);
who
% for loops
for k=1:5
k
end
for k=1:2:10
k
end
mysin(pi)
mysin(linspace(-pi,pi,5))
% while loops
i=1;
while i <= 5
i
i=i+1;
end
x=mynewt(5)
x=mynewt(7)
% if statements
r=randi(100);
if isprime(r)
disp([num2str(r),’ is prime’])
else
disp(’r is not prime’)
factors=factor(r)
end
rand3
% simple plotting
x=linspace(0,2*pi,1000);
plot(x,sin(x),x,cos(x),’r--’,’LineWidth’,2)
help plot
xlabel(’x’)
ylabel(’sin(x) and cos(x)’)
title(’Trig functions’)
legend(’sin(x)’,’cos(x)’,’Location’,’SouthWest’)
shg
figure
fplot(’sin(x)’,[0,2*pi])
fplot(’cos(x)’,[0,2*pi],’k-.’)
hold on
fplot(’sin(x)’,[0,2*pi])
close(1)
close all
f = @(x) sin(x)-cos(x)+exp(-x)
fplot(f,[0,20])
grid
hold on
fplot(’0’,[0,20],’r’)
% Root finding and Optimisation
fzero(f,4)
f(ans)
fzero(f,7)
[x,fval]=fzero(f,10)
[x,fval]=fminbnd(f,4,6)
[x,fval]=fminbnd(f,10,12)
x=fminbnd(@(x)-f(x),0,4)
fmax=f(x)
% file g.m
function y=g(x)
y=sin(x^5)+cos(x^4);
fplot(’g’,[-pi/2,pi/2])
fzero(’g’,1)
[x,gval]=fminbnd(’g’,-pi/2,pi/2)
[x,gval]=fminbnd(’g’,1,1.5)
c=[6 -23 30 -30 24 -7]
roots(c)
% file timelinsolve.m
% this script times how long it takes to solve a linear system
% using backslash and inv
n=1000;
A=randn(n);
b=randn(n,1);
tic, x1=A\b; toc
tic, x2=inv(A)*b; toc
% file timelinsolvefun.m
% this function times how long it takes to solve a linear system
% using backslash and inv, it takes matrix size as an input
function timelinsolvefun(n)
A=randn(n);
b=randn(n,1);
tic, x1=A\b; toc
tic, x2=inv(A)*b; toc
end
% file timelinsolvefun2.m
% this function times how long it takes to solve a linear system
% using backslash and inv, it takes matrix size as an input and outputs the solutions
function [x1,x2]=timelinsolvefun2(n)
A=randn(n);
b=randn(n,1);
tic, x1=A\b; toc
tic, x2=inv(A)*b; toc
end
% file mysin.m
% this function approximates sin(x) using the first 21 terms in the power series
function sinx=mysin(x)
sinx=0*x;
for k=0:20
sinx=sinx+(-1)^k*x.^(2*k+1)/factorial(2*k+1);
end
end
% file mynewt.m
% this function finds a root of sin(x)-cos(x)+exp(-x) using Newton’s method
function x=mynewt()
f=@(x) sin(x)-cos(x)+exp(-x);
fprime=@(x) cos(x)+sin(x)-exp(-x);
x=xguess;
tol=1e-10;
while abs(f(x)) > tol
x=x-f(x)/fprime(x)
end
end
% file rand3.m
% this script generates 3 random numbers and states a fact about them
r=randi(10,1,3)
if (r(1) == r(2) & r(2) == r(3))
disp(’all the integers are the same’)
elseif (r(1) == r(2) | r(1) == r(3))
disp(’r(1) is the same as one of the other integers’)
elseif (r(1) > r(2) && r(1)>r(3))
disp(’r(1) is the biggest of the integers’)
else
disp(’either r(2) or r(3) is the biggest’)
end