This commit is contained in:
lda committed 2025-06-14 03:52:53 +00:00
1 parent e7c5e46421
commit bb5767833b
5 files changed
+45

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
function [T,Y]= forwardEuler (yprime, tspan,h,y0)
% function [T,Y]= forwardEuler (yprime, tspan,h,y0)
% Computes the numerical solution of an ODE using the forward Euler method.
% yprime: handle of function defining the ODE.
% tspan = [tmin tmax]: interval over which solution has to be computed
% h: time step
% y0: initial condition
% Output:
% T: sequence of time steps
% Y: values of y at each time step
% Initializing our interval with the first time value:
T(1) = tspan(1);
% Initializing our solution with the initial condition or guess:
Y(1) = y0;
% Initializing n:
n=1;
while T(n) < tspan(2)
% Advancing time by the input time step:
T(n+1) = T(n) + h;
% Evaluating the solution at the next time step:
Y(n+1) = Y(n) + h * yprime(T(n), Y(n));
% Incrementing n:
n=n+1;
end
end
BIN
View File
Binary file not shown.
+13
View File
@@ -0,0 +1,13 @@
%% Ex. 1: solve for min of x^3 e^-x.
options=optimset('Display','Iter','TolFun',1e-8);
f1 = @(x) x.^3 .* exp(-x)
[x, fv, e, o] = fminbnd(f1, 1, 5, options);
disp("its: " + o.iterations)
fplot(f1, [1 4])
%% Ex2: min of xy e(-(x2+y2))
f2 = @(xy) xy(1).*xy(2).*exp(-(xy(1).^2+xy(2).^2))
[x, fv, e, o] = fminsearch(f2, [1 -1], options);
disp("its: " + o.iterations)
fsurf(@(x, y)f2([x, y]), [-2 2 -2 2])
BIN
View File
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
function yprime_val = yprime(t,y)
% ODE function for Exercise 5
yprime_val = t.^2 + y; %
end