Simbolička Matematika: M. Essert: Matlab Inženjerski
Simbolička Matematika: M. Essert: Matlab Inženjerski
Simbolička Matematika: M. Essert: Matlab Inženjerski
SIMBOLIČKA MATEMATIKA
7.1
syms x % x is a symbolic variable
f = 3*x^2 - 5*x + 1 % sym expression
g = x^2 + 2*x % so is g
f + g
ans =
4*x^2-3*x+1
7.2
x = 5 % x has a numeric value
f = 3*x^2 - 5*x + 1
f =
51
ezplot(f, [- 3,2])
subs(f, x, - 2)
ans =
23
7.3
syms q
subs(f, x, q)
ans =
3*q^2-5*q+1
8.1 ans =
syms x 3*x^2-2*a*x
g = x^2*cos(x)
g = diff(x^3 - a*x^2 + 2, a)
x^2*cos(x) ans =
-x^2
8.2
diff(g, x)
ans = 8.6
2*x*cos(x)-x^2*sin(x) gp=diff(g, x) % dg/dx (x=2.1)
gp =
8.3 2*x*cos(x)-x^2*sin(x)
diff(g, x, 2)
ans = subs(gp, x, 2.1)
2*cos(x)-4*x*sin(x)-x^2*cos(x) ans =
-5.9271
8.4
diff(x^3-x^2+2, x) subs(diff(g, x), x , 2.1 )
ans = ans =
3*x^2-2*x -5.9271
8.5 8.7
syms a syms t
diff(x^3 - a*x^2 + 2, x) DE1 = ' Dy = y*(1 - y) '
23
DE1 = pretty(ysol) % Gives nice format
Dy = y*(1 - y)
1
ysol = dsolve(DE1) --------------
ysol = 1 + exp(-t) C1
1/(1+exp(-t)*C1)
ysol =
8.8 1/(1+exp(-t)*C1)
dysol = simple( diff(ysol) ) pretty(ysol) % Gives nice format
dysol =
1/(1+exp(-t)*C1)^2*exp(-t)*C1 1
pretty(dysol) % Gives nice format --------------
1 + exp(-t) C1
exp(-t) C1
-----------------
2 8.12
(1 + exp(-t) C1) dysol = simple( diff(ysol) )
dysol =
1/(1+exp(-t)*C1)^2*exp(-t)*C1
8.9 pretty(dysol) % Gives nice format
h = dsolve( DE1, ' y(0) = 1/10 ' )
h = exp(-t) C1
1/(1+9*exp(-t)) -----------------
pretty(h) % Gives nice format 2
(1 + exp(-t) C1)
1
-------------
1 + 9 exp(-t) 8.13
h = dsolve( DE1, ' y(0) = 1/10 ' )
8.10 h =
subs(h, t, 0) 1/(1+9*exp(-t))
%To substitute t = 0 into the pretty(h) % Gives nice format
solution f. 1
ans = -------------
0.1000 1 + 9 exp(-t)
8.11
syms t
DE1 = ' Dy = y*(1 - y) ' subs(h, t, 0)
DE1 = ans =
Dy = y*(1 - y) 0.1000
ysol = dsolve(DE1)
9.1
lotka.m
function yp = lotka(t,y)
%LOTKA Lotka-Volterra predator-prey model.
global ALPHA BETA
yp = [y(1) - ALPHA*y(1)*y(2); -y(2) + BETA*y(1)*y(2)];
=======================================================
9.2
twotnk.m
function hdot = twotnk(t,h)
% To solve
% dh1/dt = 1 - 0.5*sqrt(h1-h2)
% dh2/dt = 0.25*sqrt(h1-h2) - 0.25*sqrt(h2)
hdot = zeros(2,1); % a column vector
hdot(1) = 1- 0.5*sqrt(h(1)-h(2));
hdot(2) = 0.25*sqrt(h(1) - h(2)) - ...
0.25*sqrt(h(2));
===============================================
9.3
g1.m
function dy = g1(x,y)
dy = 3*x^2;
[x,num_y]=ode23('g1',[2 4],0.5);
an1_y=x.^3-7.5;
subplot(221),plot(x,num_y,x,an1_y,'o'),...
title('Solution to Equation 1'),...
xlabel('x'), ylabel('y=f(x)'), grid
g2.m
function dy = g2(x,y)
dy = -0.131*y;
clear g2
[x,num_y]=ode23('g2',[0 5],4);
an1_y=4*exp(-0.131*x);
subplot(222),plot(x,num_y,x,an1_y,'o'),...
title('Solution to Equation 2'),...
xlabel('x'), ylabel('y=f(x)'), grid
g3.m
function dy = g3(x,y)
dy = 3.4444e-05- 0.0015*y;
clear g3
[x,num_y]=ode23('g3',[0 120],0.0022);
25
an1_y=0.022963-0.020763*exp(-0.0015*x);
subplot(223),plot(x,num_y,x,an1_y,'o'),...
title('Solution to Equation 3'),...
xlabel('x'), ylabel('y-f(x)'), grid
g4.m
function dy = g4(x,y)
dy = 3*y+exp(2*x);
clear g4
[x,num_y]=ode23('g4',[0 3],3);
an1_y=4*exp(3*x)-exp(2*x);
subplot(224),plot(x,num_y,x,an1_y,'o'),...
title('Solution to Equation 4'),...
xlabel('x'), ylabel('x=f(x)'), grid
=======================================================
9.4
spr_damp.m
% Definition of Spring-Damper system
% M*x'' + D*x' + K*x = f(t) or x'' + (D/M)*x' + (K/M)*x = f(t)/M
% or expressed as a system of first-order ODEs:
% x1' = x2
% x2' = (1/M)*f(t) - D*x2 - K*x1
% where f(t) is defined by a function named in a string variable, FORCEFUN
function xdot = spr_damp(t,x)
global M D K FORCEFUN
xdot(1,:) = x(2);
xdot(2,:) = (1/M)*( feval(FORCEFUN,t) - D*x(2) - K*x(1) );
delaysin.m
% Sinusoidal forcing function for spring-mass-damper problem, smd_prob.m
function f = delaysin(t)
global FIRSTCALL AMPLITUDE DELAY
if FIRSTCALL ~= 1,
AMPLITUDE = input('Amplitude of forcing sine wave: ')
DELAY = input('Delay time: ')
FIRSTCALL=1;
end;
if t >= DELAY,
f = AMPLITUDE*sin(t-DELAY);
else
f = 0;
end;
smdprob.m
eps1 = 0.001; % example of first forward
global M D K FORCEFUN FIRSTCALL AMPLITUDE DELAY
% initialize Mass (M), Damping Coeff. (D), and Spring Constant (K):
M=2, D=1.656, K=40
% Set the flag which indicates where the forcing funtion has been called:
FIRSTCALL=0;
% Define the forcing function by asking user for the name of an m-file
Računalna matematika, FSB Zagreb, 2008.
M. Essert: Matlab inženjerski 27
clear smdprob M =
smdprob 2
M = D =
2 1.6560
D = K =
1.6560 40
FORCEFUN =
delaysin
t0 =
0
tf =
10
x0 =
1
0
AMPLITUDE =
100
Delay time: 0
DELAY =
0
smdprob
27
28 M. Essert: Matlab programski i grafički
9.5
de_fn.m
function z=de_fn(x,y)
z=-x*y;
run_de.m
clear
% this program calls the function file de_fn.m
a=input('left end point a = ');
b=input('right end point b = ');
N=input(' number of sub-intervals, N = ');
ya=input('initial value at x=a, ya= ');
h=(b-a)/N;
x=a+h*(1:(N+1));
lx=length(x);
y(1)=ya;
for j=1:N
y(j+1)=y(j)+h*de_fn(x(j),y(j));
end
plot(x,y)
-------------------------------------------------
de2_fn.m
function z=de2_fn(x,y,yp)
z=-x*y/(yp^2+1);
run_de2.m
clear
% this program calls the function file de2_fn.m
a=input('left end point a = ');
b=input('right end point b = ');
N=input(' number of sub-intervals, N = ');
ya=input('initial value at x=a, y(a)= ');
yap=input('initial value at x=a, y''(a)= ');
h=(b-a)/N;
x=a+h*(1:(N+1));
lx=length(x);
w(1)=ya;
z(1)=yap;
for j=1:N
w(j+1)=w(j)+h*z(j);
z(j+1)=z(j)+h*de2_fn(x(j),w(j),z(j));
end
y=w;
plot(x,y)
=======================================================
9.6
lorenzde.m
function dy=lorenzde(t,y)
dy=[10*(y(2)-y(1)); (28-y(3)).*y(1)-y(2); y(1).*y(2)-(8/3)*y(3)];
run lorenz.m
clear
t0=input(' initial time t0 = ');
T=input(' final time T = ');
% initial condition; e.g. [1 -1 2]'
v=input(' vector of initial conditions v = [v1,v2,v3] ');
[n,m]=size(v);
if m>1
v=v';
end
tvec=t0:.025:T;
[t,y]=ode45('lorenzde',tvec,v);
h1=figure
plot(y(:,1),y(:,2))
h2=figure
plot(y(:,1),y(:,3))
h3=figure
plot(y(:,2),y(:,3))
=======================================================
9.7
vdpde.m
function yp = vdpde(t,y)
global MU
yp(1)=y(2);
yp(2)=MU*y(2).*(1-y(1).^2)-y(1);
run_vdpe.m
clear
clear global
global MU
t0=input(' initial time t0 = ');
T=input(' final time T = ');
MU=input(' parameter MU = ');
v=input(' vector of initial conditions v = [v1,v2] ');
[n,m]=size(v);
if m>1
v=v';
end
tvec=t0:.025:T;
[t,y]=ode45('vdpde',tvec,v);
plot(y(:,1),y(:,2))
=======================================================
KVADRATURA (INTEGRACIJA)
int(a*sin(x), a) int(1/(1+x^2), x, 0, 1)
ans = ans =
1/2*a^2*sin(x) 1/4*pi
=======================================================
10.1
fxlog.m
function f=fxlog(x)=x .* log(x);
10.2
fxy.m
function out=fxy(x,y)
out=y^2 * exp(x)+x*cos(y);
TVORBA TABLICA
11.1
% Script file SineTable.m
%
% Ispisuje kratku tablicu proračuna sinusa.
%
n = 21;
x = linspace(0,1,n);
y = sin(2*pi*x);
disp(' ')
disp(' k x(k) sin(x(k))')
disp('------------------------')
for k=1:21
degrees = (k-1)*360/(n-1);
disp(sprintf(' %2.0f %3.0f %6.3f'...
,k,degrees,y(k)));
end
disp( ' ');
disp('x(k) je dan u stupnjevima.')
disp(sprintf('Jedan stupanj = %5.3e radijana',pi/180))
11.2
% Script File Zoom
%
% Nacrtajte (x-1)^6 uz točku x=1 sa
% slijedno povećanom skalom.
% Izračunavanje (x-1)^6 preko
% x^6 - 6x^5 + 15x^4 - 20x^3 + 15x^2 - 6x +1
% dovodi do ozbiljnih promišljanja.
close all
k=0;
for delta = [.1 .01 .008 .007 .005 .003 ]
x = linspace(1-delta,1+delta,100)';
y = x.^6 - 6*x.^5 + 15*x.^4 - 20*x.^3 ...
+ 15*x.^2 - 6*x + ones(100,1);
k=k+1;
subplot(2,3,k)
plot(x,y,x,zeros(1,100))
axis([1-delta 1+delta -max(abs(y)) max(abs(y))])
end
LINEARNE JEDNADŽBE
12.1
Rješavanje sustava jednadžbi preko 'backslash'-a.
A=[3 1; 5 2] % definiraj A
b=[2;-9] % definiraj b
x=A\b % riješi Ax=b
A*x-b % provjeri rezultat
12.2
A=[3 1; 5 2] % definiraj A
b=[2; -9] % definiraj b
C=[A b] % postavi augmentiranu matricu
rref(C) % izračunaj reduciranu echleon formu
% posljednji stupac je rješenje
12.3
a=rand(1000);
b=rand(1000,1);
tic, x=a\b; toc
elapsed_time =
0.8130
D O D A T A K
NELINEARNE JEDNADŽBE
13.1
fcn1.m
function y = fcn1(x)
% To solve f(x) = x^2 - 2x - 3 = 0
y = x^2 - 2*x - 3;
y1 = fzero('fcn1', 0)
y1 =
-1
13.2
nle.m
function f = nle(x)
% To solve
% f1(x1,x2) = x1^2 - 4x1^2 - x1x2 = 0
% f2(x1,x2) = 2x^2 - x2^2 + 3x1x2 = 0
f(1) = x(1) - 4*x(1)*x(1) - x(1)*x(2);
f(2) = 2*x(2) - x(2)*x(2) + 3*x(1)*x(2);
clear nle
x0 = [1 1]';
x = fsolve(@nle, x0,optimset('fsolve'))
Optimization terminated successfully:
First-order optimality is less than options.TolFun.
x =
0.2500
0.0000
13.3
newton.m
function x = newton(fcn, xguess, xtol, ftol, maxiter)
% ----------------------------------------------------------------------
% Usage: x = newton('fcn', xguess, xtol, ftol, maxiter)
% Vanilla Newton-Raphson's method to solve an algebraic equation of the form:
% f(x)=0
% Variables:
% fcn ... Name M-file that specifies the function to be solved f(x) and
% its Jacobian dfdx(x). It should be enclosed in a pair of single
% Newton's Method
xold=x;
x = x-inv(dfdx)*f;
myfxeq0.m
dfdx(1,2)= 2.*y + x;
dfdx(2,1)= 3.;
dfdx(2,2)= 1. - 3.*y*y;
% ----------------------------------------------------------------------
% Solve the following set of nonlinear algebraic equations with the Newton's
% method by calling "newton" function.
% y^2 + x*y - 1 = 0
% 3*x + y + 1 - y^3 = 0
% Instructor: Nam Sun Wang
% ----------------------------------------------------------------------
myfxeq04.m
function [f, dfdx] = myfxeq04(xvect)
% ----------------------------------------------------------------------
% Specify 3-dimensional f(xvect)=0
% sin(x) + y^2 + ln(z) - 7 = 0
% 3*x + 2^y - z^3 + 1 = 0
% x + y + z - 5 = 0
% Instructor: Nam Sun Wang
% ----------------------------------------------------------------------
% ----------------------------------------------------------------------
% Solve the following set of nonlinear algebraic equations with the Newton's
% method by calling "newton" function.
% sin(x) + y^2 + ln(z) - 7 = 0
% 3*x + 2^y - z^3 + 1 = 0
% x + y + z - 5 = 0
% Instructor: Nam Sun Wang
% ----------------------------------------------------------------------
myfxeq05.m
function f = myfxeq05(xvect)
% ----------------------------------------------------------------------
% Specify 3-dimensional f(xvect)=0
% sin(x) + y^2 + ln(z) - 7 = 0
% 3*x + 2^y - z^3 + 1 = 0
% x + y + z - 5 = 0
% This file is called by newton5.m
% Instructor: Nam Sun Wang
% ----------------------------------------------------------------------
% ----------------------------------------------------------------------
% Solve the following set of nonlinear algebraic equations with "fsolve"
% sin(x) + y^2 + ln(z) - 7 = 0
% 3*x + 2^y - z^3 + 1 = 0
% x + y + z - 5 = 0
% Instructor: Nam Sun Wang
% ----------------------------------------------------------------------
A=[ -2 1 0 0 0
1 -2 1 0 0
0 1 -2 1 0
0 0 1 -2 1
0 0 0 1 -2 ];
S=sparse(A)
i=[ 1 2 1 2 3 2 3 4 3 4 5 4 5];
j=[ 1 1 2 2 2 3 3 3 4 4 4 5 5];
s=[-2 1 1 -2 1 1 -2 1 1 -2 1 1 -2];
a=sparse(i,j,s,5,5) (5,4) 1
a = (4,5) 1
(1,1) -2 (5,5) -2
(2,1) 1
(1,2) 1 B=full(a)
(2,2) -2 B =
(3,2) 1 -2 1 0 0 0
(2,3) 1 1 -2 1 0 0
(3,3) -2 0 1 -2 1 0
(4,3) 1 0 0 1 -2 1
(3,4) 1 0 0 0 1 -2
(4,4) -2
K=eye(5)
K =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
K2=speye(5)
K2 =
(1,1) 1
(2,2) 1
(3,3) 1
(4,4) 1
(5,5) 1
help sparse
see also: SPALLOC, SPONES, SPEYE,
SPCONVERT, FULL, FIND, SPARFUN.
n=5; e=ones(n,1);
A=spdiags([-e 4*e -e],[-1 0],n,n);
full(A)
POSEBNE KRIVULJE
bezier.m
% Bezier cubic curve
% This file will create a Bezier cubic curve and dispay the plot
% There are two reasons for including comments in the front.
% If you are working with a lot of programs then this will tell you
what
% the file is supposed to accomplish.
% Second, if you type help filename ( without the .m extension) then
these
% comments are displayed in the workspace
Polyerr.m
function max_err=polyerr(n)
% POLYERR Error in linear interpolation polynomial.
% POLYERR(N) is an approximation based on N sample points
% to the maximum difference between subfunction F and its
% linear interpolating polynomial at 0 and 1.
max_err=0;
f0=f(0); f1=f(1);
for x=linspace(0,1,n)
p=x*f1 + (x-1)*f0;
Računalna matematika, FSB Zagreb, 2008.
M. Essert: Matlab programski 41
err=abs(f(x)-p);
max_err=max(max_err,err);
end
% Subfunction
function y=f(x)
%F Function to be interpolated, F(X).
y=sin(x);
>> polyerr(5)
ans =
0.0587
>> polyerr(50)
ans =
0.0600