Anda di halaman 1dari 19

M.

Essert: Matlab inženjerski 23

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

DIFERENCIJALNE JEDNADŽBE (ODE) - simbolički

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)

DIFERENCIJALNE JEDNADŽBE (ODE) - numerički

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)];

Računalna matematika, FSB Zagreb, 2008.


M. Essert: Matlab inženjerski 25

------- main --------------


global ALPHA BETA
ALPHA = 0.01
BETA = 0.02
[t,y] = ode23('lotka',0,10,[1; 1]);
plot(t,y)

=======================================================

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));

------- main --------------


clear twotnk
[t, h] = ode45('twotnk', [0 100], [12 7]');
plot(t, h)

===============================================

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

% or built-in function such as "sin" (this use of "input" takes a string


value):
FORCEFUN = input('Type the name of the forcing function: ','s')
% Set starting time and finishing time:
t0=0, tf=10
% Specify initial conditions:
x0=[1;0] % note: x0(1)=x(t=0), x0(2)=dx/dt(t=0)
% Solve the system of first-order ODEs
[t,x]=ode45('spr_damp',[t0,tf],x0)
% Plot the results:
hold on % keep adding additional plots to plot window
plot(t,x(:,1)); % where x(:,1) is the first column of x, x(t)
% plot zero displacement axis
plot(t,zeros(size(x(:,1))),'w-');
% add titles
title('Forced, Damped Oscillator');
xlabel('Time in seconds');
ylabel('Displacement');
hold off

clear smdprob M =
smdprob 2
M = D =
2 1.6560

D = K =
1.6560 40

K = Type the name of the forcing


40 function: sin

FORCEFUN =

delaysin

t0 =
0

tf =
10

x0 =
1
0

Amplitude of forcing sine wave: 100

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)];

Računalna matematika, FSB Zagreb, 2008.


M. Essert: Matlab primjene 29

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))

=======================================================

Computer Mathematics, FSB Zagreb, 2003.


30 M. Essert: Matlab programski i grafički

KVADRATURA (INTEGRACIJA)

syms x int(x*sin(x), x, 0, pi/2)


int(x*sin(x), x) ans =
ans = 1
sin(x)-x*cos(x)
double( int(sin(x^5 + x^3), x, 0,
diff(ans, x) pi/2) )
ans = Warning: Explicit integral could
x*sin(x) not be found.
> In
syms a C:\MATLAB6P5\toolbox\symbolic\@sym\
int(a*sin(x), x) int.m at line 58
ans = ans =
-a*cos(x) 0.2910

int(a*sin(x), a) int(1/(1+x^2), x, 0, 1)
ans = ans =
1/2*a^2*sin(x) 1/4*pi

int(sin(x^2), x) int(1/(1+x^2), x, 0, Inf)


ans = ans =
1/2*pi
1/2*2^(1/2)*pi^(1/2)*FresnelS(2^(1/
2)/pi^(1/2)*x) int(1/(1+x^4), x, 0, Inf)
ans =
1/4*pi*2^(1/2)

=======================================================

10.1
fxlog.m
function f=fxlog(x)=x .* log(x);

quad(@fxlog,2,4) % quad(fun,a,b,tol) Simpson, Newton-Cotes, Gauss

10.2
fxy.m
function out=fxy(x,y)
out=y^2 * exp(x)+x*cos(y);

dblquad(@fxy,0,1,4,6) % dvostruki integral


%trapezno pravilo integracije
x=linspace(0,2*pi,10);
f=sin(x).^2 ./ sqrt(1+cos(x).^2);
trapz(x,f)

Računalna matematika, FSB Zagreb, 2008.


M. Essert: Matlab primjene 31

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

Računalna matematika, FSB Zagreb, 2008.


32 M. Essert: Matlab programski i grafički

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

A=[3 1;5 2] % definiraj A


c=[2 -9] % definiraj c
x=inv(A)*c'
A*x-c' % provjeri rezultat

12.3
a=rand(1000);
b=rand(1000,1);
tic, x=a\b; toc

elapsed_time =
0.8130

Računalna matematika, FSB Zagreb, 2008.


M. Essert: Matlab primjene 33

D O D A T A K
NELINEARNE JEDNADŽBE

syms a b c t % Create symbolics


g = a*t^2 + b*t + c
g =
a*t^2+b*t+c
solve(g, t) % Solve g = 0 for t
ans =
[ 1/2/a*(-b+(b^2-4*a*c)^(1/2))]
[ 1/2/a*(-b-(b^2-4*a*c)^(1/2))]

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

Računalna matematika, FSB Zagreb, 2008.


34 M. Essert: Matlab programski i grafički

% quotes in the calling program.


% This function should return the value of f as a column vector
% and dfdx as a matrix:
% function [f dfdx]=fcn(x)
% xguess ... initial guess of x as a column vector
% xtol ... normalized tolerance in the x-direction (stop criterion)
% sqrt of sum of squared values of x-xold for each iteration
% ftol ... sqrt of sum of squared values of f at x (stopping criterion)
% maxiter ... maxmum number of iterations allowed
% Algorithm: iterate on x = x-inv(dfdx)*f
% Instructor: Nam Sun Wang
% ----------------------------------------------------------------------

% Start with the initial guess


x = xguess;

% Iterate for a maximum number of maxiter times


for i=1 : maxiter

% Evaluate the function and its derivative at the given x


[f dfdx] = feval(fcn,x);

% Newton's Method
xold=x;
x = x-inv(dfdx)*f;

% Apply stop criterion


if ( norm(x-xold) <= xtol | norm(f) <= ftol )
return
end
end

myfxeq0.m

function [f, dfdx] = myfxeq0(xvect)


% ----------------------------------------------------------------------
% Specify 2-dimensional f(xvect)=0
% Instructor: Nam Sun Wang
% ----------------------------------------------------------------------

% Create a column vector f and a square Jacobian matrix dfdx


f = zeros(2,1);
dfdx = zeros(2,2);

% Use my own variables


x = xvect(1);
y = xvect(2);

% Specify two equations f


f(1) = y^2 + x*y - 1;
f(2) = 3*x + y + 1 - y^3;

% Specify the Jacobian dfdx


dfdx(1,1)= y;
Računalna matematika, FSB Zagreb, 2008.
M. Essert: Matlab primjene 35

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
% ----------------------------------------------------------------------

% Start fresh ----------------------------------------------------------


clear all

% Program header -------------------------------------------------------


disp('Solve the following set of nonlinear algebraic equations:')
disp(' y^2 + x*y - 1 = 0')
disp(' 3*x + y + 1 - y^3 = 0')
disp(' ')

% Provide an initial guess (work in column vectors) --------------------


xguess=[1 0]';

% Call a routine to solve for the root of f(x)=0 -----------------------


xvect = newton('myfxeq0', xguess, 1.e-6, 1.e-6, 100);

% Print out the results in the original notation -----------------------


x = xvect(1);
y = xvect(2);
disp('The roots are: ')
disp([' x = ', num2str(x) ])
disp([' y = ', num2str(y) ])

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
% ----------------------------------------------------------------------

% Create a column vector f and a square Jacobian matrix dfdx


f = zeros(3,1);
dfdx = zeros(3,3);

% Use my own variables


x = xvect(1);
y = xvect(2);
z = xvect(3);

% Specify three equations f

Računalna matematika, FSB Zagreb, 2008.


36 M. Essert: Matlab programski i grafički

f(1) = sin(x) + y*y + log(z) - 7;


f(2) = 3*x + 2^y - z*z*z + 1;
f(3) = x + y + z - 5;
% Specify the Jacobian dfdx
dfdx(1,1) = cos(x);
dfdx(1,2) = 2*y;
dfdx(1,3) = 1/z;
dfdx(2,1) = 3;
dfdx(2,2) = log(2)*2^y;
dfdx(2,3) = -3*z*z;
dfdx(3,1) = 1;
dfdx(3,2) = 1;
dfdx(3,3) = 1;

% ----------------------------------------------------------------------
% 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
% ----------------------------------------------------------------------

% Start fresh ----------------------------------------------------------


clear all

% Program header -------------------------------------------------------


disp('Solve the following set of nonlinear algebraic equations:')
disp(' sin(x) + y^2 + ln(z) - 7 = 0 ')
disp(' 3*x + 2^y - z^3 + 1 = 0 ')
disp(' x + y + z - 5 = 0 ')
disp(' ')

% Provide an initial guess (work in column vectors) --------------------


xguess=[1 1 1]';

% Call a routine to solve for the root of f(x)=0 -----------------------


xvect = newton('myfxeq04', xguess, 1.e-6, 1.e-6, 100);

% Print out the results in the original notation -----------------------


x = xvect(1);
y = xvect(2);
z = xvect(3);
disp('The roots are: ')
disp([' x = ', num2str(x) ])
disp([' y = ', num2str(y) ])
disp([' z = ', num2str(z) ])

Računalna matematika, FSB Zagreb, 2008.


M. Essert: Matlab primjene 37

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
% ----------------------------------------------------------------------

% Create a column vector f


f = zeros(size(xvect));

% Use my own variables


x = xvect(1);
y = xvect(2);
z = xvect(3);

% Specify three equations f


f(1) = sin(x) + y*y + log(z) - 7;
f(2) = 3*x + 2^y - z*z*z + 1;
f(3) = x + y + z - 5;

% ----------------------------------------------------------------------
% 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
% ----------------------------------------------------------------------

% Start fresh ----------------------------------------------------------


clear all

% Program header -------------------------------------------------------


disp('Solve the following set of nonlinear algebraic equations:')
disp(' sin(x) + y^2 + ln(z) - 7 = 0 ')
disp(' 3*x + 2^y - z^3 + 1 = 0 ')
disp(' x + y + z - 5 = 0 ')
disp(' ')

% Provide an initial guess (work in column vectors) --------------------


xguess=[1 1 1]';

% Call a routine to solve for the root of f(x)=0 -----------------------


xvect = fsolve(@myfxeq05, xguess, foptions); %old sintax

% Print out the results in the original notation -----------------------


x = xvect(1);
y = xvect(2);
z = xvect(3);

Računalna matematika, FSB Zagreb, 2008.


38 M. Essert: Matlab programski i grafički

disp('The roots from the default "fsolve" are: ')


disp([' x = ', num2str(x) ])
disp([' y = ', num2str(y) ])
disp([' z = ', num2str(z) ])

% Repeat with a different set of options -------------------------------


options(2) = 1.e-6; %Tolerance for x
options(3) = 1.e-6; %Tolerance for f
options(5) = 1; %Levenberg-Marquardt Method
xvect = fsolve('myfxeq05', xguess, options);

% Print out the results in the original notation -----------------------


x = xvect(1);
y = xvect(2);
z = xvect(3);
disp('The roots from "fsolve" with Levenberg-Marquardt are: ')
disp([' x = ', num2str(x) ])
disp([' y = ', num2str(y) ])
disp([' z = ', num2str(z) ])

SLABO KONDICIONIRANE (SPARSE, RASPRŠENE) MATRICE

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

C=sparse(B) % pretvroba u sparse


nnz(a) % broj elemenata različitih od nule

Računalna matematika, FSB Zagreb, 2008.


M. Essert: Matlab primjene 39

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)

Računalna matematika, FSB Zagreb, 2008.


40 M. Essert: Matlab programski

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

BCon3 = [-1 3 -3 1; 3 -6 3 0; -3 3 0 0 ; 1 0 0 0 ]; % our 4 X 4


constant Matrix

BezVert3 = [ 0 0 ; 0.3 0.5 ; 0.5 0.7 ; 1.0 1.0]; % the vertices


for i = 1:1:50 % for loop 1 - 50 in steps of 1
par = (i - 1)/49;
XY(i,:) = [par^3 par^2 par 1]*BCon3*BezVert3; % we created our
data
end
XY
% we will display the vertices and the curve using
% Matlabs built-in graphic functions
clf % this will clear the figure
plot(BezVert3(:,1),BezVert3(:,2),'ro',XY(:,1),XY(:,2),'b-')
xlabel(' x value')
ylabel ('y value')
title('Cubic Bezier Curve')
legend('Vertex','Curve') % you can move the legend
coeff = polyfit(XY(:,1),XY(:,2),1) % a linear fit
plot(XY(:,1),polyval(coeff,XY(:,1)),'--')
hold on % allows multiple plots on the same figure
plot(XY(:,1),XY(:,2),'r-')
grid % draws the grid
xlabel('x value')
ylabel('y value')
title(' curve fit example')
area1 = trapz(XY(:,1),XY(:,2))

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);

>> help polyerr/f


F Function to be interpolated, F(X).

>> polyerr(5)
ans =
0.0587

>> polyerr(50)
ans =
0.0600

Računalna matematika, FSB Zagreb, 2008.

Anda mungkin juga menyukai