Numerical Methods
fminbnd: Single-variable bounded nonlinear function minimization.
fminsearch: Multidimensional unconstrained nonlinear minimization (Nelder-Mead).
clear; format compact
% Construct the matrix y = [5; -8; 0]; A = [3, 2, -1; -3, -1, 1; 1, -1, 1]; % Check the rank and determinant of A r = rank(A) % The number of linearly independent rows or columns d = det(A) % Square matrix determinant A_inv = inv(A) % Matrix inverse% Solve the system of linear equations x = inv(A) * y
r = 3 d = 4 A_inv = 0 -0.2500 0.2500 1.0000 1.0000 0 1.0000 1.2500 0.7500 x = 2 -3 -5
A = [3, 2, 1; 7, 2, 5; 9, 9, 8]; [L, U, P] = lu(A) % L*U = P*A
L = 1.0000 0 0 0.7778 1.0000 0 0.3333 0.2000 1.0000 U = 9.0000 9.0000 8.0000 0 -5.0000 -1.2222 0 0 -1.4222 P = 0 0 1 0 1 0 1 0 0
P = [1, 0, -4]; % x^2 -4%Get the roots of a polynomial r = roots(P) %Get the polynomial from the roots Pr = poly(r) %Evaluate a polynomial at many points x0 = [1, 2, 3]; y0 = polyval(P, x0)
r = 2.0000 -2.0000 Pr = 1.0000 -0.0000 -4.0000 y0 = -3 0 5
X = [-2, 1, 3]; Y = [0, 5, 2]; p2 = polyfit(X, Y, 2) %Plot to see the fitting figure; plot(X, Y, 'ro', 'MarkerSize', 10); hold on; x0 = -3:0.1:4; plot(x0, polyval(p2, x0), 'r--');
p2 = -0.6333 1.0333 4.6000
x(1) = 1; %set initial value maxit = 2000; %set maximum iterationsfor i = 1:maxit x(i+1) = exp(-x(i)); %update value with x(i+1) = g(x(i)) if abs(x(i+1)-x(i)) < 1e-10 break; %break if within limit endendif i==maxit sprintf('Warning: maximum number of iteration reached \n') end sprintf('After %g iterations, the solution is %g \n', i, x(i))
ans = After 41 iterations, the solution is 0.567143
clear; x0 = [-0.001; -0.001]; %Initial guess maxit = 1000; %Max iteration crit = 1e-3; %Accuracy critirion param = [1 4 4 1]; %syseqa1 parameters%Find roots using Newton method sol = Newton('syseqa1', x0, param, crit, maxit) f_sol = syseqa1 (sol, param) %confirm the roots f(sol)=0
sol = -3.9684 -0.2520 f_sol = 1.0e-12 * -0.5574 -0.3298
x = fzero('myfunc1', 1) x = fzero(@(x) (cos(exp(x)) + x.^2 - 1), 1)
x = 1.3367 x = 1.3367
% Find the minimum of the function f(x) = x^3 – 2x – 5 on the interval (0,2) f = @(x)x.^3-2*x-5; [x_m, fval] = fminbnd(f, 0, 2) % Plot the function to visualize the minimum xx = 0:0.1:2; y = f(xx); figure; plot(xx, y, x_m, fval, 'ro');
x_m = 0.8165 fval = -6.0887
f = @(x) 2 + x(1) - x(2) + 2*x(1)^2 + 2*x(1)*x(2) + x(2)^2; [x_m, fval] = fminsearch(f, [-0.5, 0.5])
x_m = -1.0000 1.5000
fval = 0.7500
fun = @(x) 100*(x(2)-x(1)^2)^2 + (1-x(1))^2; %define the objective function x0 = [-1,2]; A = [1,2]; b = 1; x = fmincon(fun,x0,A,b)
Local minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the default value of the function tolerance, and constraints are satisfied to within the default value of the constraint tolerance. x = 0.5022 0.2489