Professional Documents
Culture Documents
Trong h phng trnh vi phn cp mt, cc hm v phi fj(x, y1, y2, ..., yn) c th khuyt mt
vi bin, v vy ta cn vit mt hm thay th n + 1 gi tr [vx, v1, v2, ..., vn] vo n + 1 bin, nhng
ch nhng bin c mt trong fj mi c thay.
Trc ht ta vit hm msub(expr, vars, vals) tr li gi tr cho biu thc expr khi thay cc bin
trong vars bi cc gi tr tng ng trong vals. V hm ny s c gi vi di ca vars bng
di ca vals nn trong thn hm ta b qua vic kim tra. Ch rng cc bin trong biu thc
expr ch gm x, y1, y2, y3, ... V d:
msubs('y1 + 2*y2 - 4*x', 'x, y1, y2', [1, 2, 3]) bng 4,
msubs('y1 + 2*y2', 'x, y1, y2', [1, 2, 3]) bng 8.
function out = msubs(expr, vars, vals)
out = expr; n = max(size(vals));
if ~isempty(strfind(vars,'x'))
out = subs(out,'x',vals(1));
end
for k = 2:n
var = ['y' num2str(k-1)];
if ~isempty(strfind(vars, var))
out = subs(out,var,vals(k));
end
end
a. Phng php Euler
Trong hm odeseuler() di y, fs l bin kiu cell lu cc hm v phi, y0 l vc t cc
gi tr u, cn n l s on chia ca on [a, b].
function [x y] = odeseuler(fs, a, b, y0, n)
m = max(size(fs)); vars = cell(m,1);
h = (b - a)/n; x = (a:h:b)'; y(1,:) = y0;
for k = 1:m
vars(k) = cellstr(findsym(sym(fs{k})));
end
for k = 1:n
for j = 1:m
y(k+1, j) = y(k, j) + h*msubs(fs{j},vars(j),[x(k), y(k,:)]);
end
end
V d, vi bi ton:
y' = x + y + z
, y(0) = 1, z(0) = 0, 0 x 1, n = 10.
z ' = 2 x + 3sin y
Li gi hm s l:
[x, y] = odeseuler({'x + y1 + y2','-2*x + 3*sin(y1)'}, 0, 1, [1, 0], 10)
V ta nhn c nghim:
x
y
z
0
1.0000
0
0.1000 1.1000 0.2524
0.2000 1.2452 0.4998