Finding Roots

Polynomial roots

$f(x) = 3 x^2 + 2 x + 1$

In [1]:
p = [3, 2, -1];
x = linspace(-2, 2, 1e3);

figure(1);
plot(x, polyval(p, x), 'LineWidth', 7);
hold on;
plot(x, zeros(1, length(x)), 'LineWidth', 7, 'Color', 'black');
plot(zeros(1, length(x)), linspace(-5, 15, length(x)), 'LineWidth', 7, 'Color', 'black');
set(gca(), 'FontSize', 18)

roots(p)
ans =

  -1.00000
   0.33333

Zeros of a univariate functions, $\texttt{fzero}$

$e^x = \log(x)$

$f(x) = e^x - \log(x)$

$f(x) = 0$

In [2]:
f = @(x) exp(x) - 20 * log(x);

figure(2);
x = linspace(0, 5, 1e3);
plot(x, f(x), 'LineWidth', 7);
hold on;
plot(x, zeros(1, length(x)), 'LineWidth', 7, 'Color', 'black');

fprintf('Trying one guess\n');
x_guess = 1.0
x_zero = fzero(f, x_guess)

fprintf('\n');

fprintf('Trying another guess\n');
x_guess = 3.0
x_zero = fzero(f, x_guess)
Trying one guess
x_guess =  1
x_zero =  1.1759

Trying another guess
x_guess =  3
x_zero =  3.1268

Zeros of a system of function, $\texttt{fsolve}$

$e^{-e^{-(x + y)}} = y (1 + x^2)$

$x \cos(y) + y \sin(x) - \frac{1}{2} = 0$

In [3]:
function F = my_fun(x)
    F = zeros(2, 1);
    
    F(1) = exp(-exp(-(x(1)+x(2)))) - x(2)*(1+x(1)^2);
    F(2) = x(1)*cos(x(2)) + x(2)*sin(x(1)) - 0.5;
end
In [4]:
F = @(x) [...
        exp(-exp(-(x(1)+x(2)))) - x(2)*(1+x(1)^2);
        x(1)*cos(x(2)) + x(2)*sin(x(1)) - 0.5...
        ];

x = fsolve(F, [2.0, 1.0])
F(x)

x = fsolve(@(x) my_fun(x), [2.0, 1.0])
my_fun(x)
x =

   0.35325   0.60608

ans =

   1.2035e-07
  -4.4508e-08

x =

   0.35325   0.60608

ans =

   1.2035e-07
  -4.4508e-08

Systems of Linear Equations

$ 3 x + 5 y + z = 0 $

$ 7 x + -2 y + 4 z = 2 $

$ -6 x + 3 y + 2 z = -1 $

In [1]:
A = [3, 5, 1; ...
     7, -2, 4; ...
     -6, 3, 2]
b = [0;
     2;
     -1]
     
x = inv(A) * b
x = pinv(A) * b
x = A \ b

fprintf('Checking how good of a solution we got');
norm(A * x - b)
A =

   3   5   1
   7  -2   4
  -6   3   2

b =

   0
   2
  -1

x =

   0.15721
  -0.12664
   0.16157

x =

   0.15721
  -0.12664
   0.16157

x =

   0.15721
  -0.12664
   0.16157

Checking how good of a solution we got
ans =    2.4825e-16
Checking how good of a solution we got
In [2]:
A = rand(50, 5);
b = rand(50, 1);

try
    x = inv(A) * b
catch ME
    fprintf('Error thrown, cannot invert a matrix that''s not square');
end
x = pinv(A) * b
x = A \ b

fprintf('Checking how good of a solution we got');
norm(A * x - b)
Error thrown, cannot invert a matrix that's not square
x =

   0.360669
   0.069326
   0.035450
   0.467089
   0.180901

x =

   0.360669
   0.069326
   0.035450
   0.467089
   0.180901

Checking how good of a solution we got
ans =  1.9393
Error thrown, cannot invert a matrix that's not squareChecking how good of a solution we got
In [ ]: