Search code examples
matlabnonlinear-functions

Solving non-linear system of equations in MATLAB


I encountered a non-linear system of equations that has to be solved. The system of equations can be written as: Ax + exp(x) = b with b a known Nx1 matrix, A a known NxN matrix, and x the unknown Nx1 vector for which has to be solved. The exp is defined element-wise on the x vector. I tried to search the MATLAB-manual but I'm having a hard time finding how to solve this kind of equations with MATLAB, so I hope someone can help me out.


Solution

  • You can use Newton-Raphson. Re-arrange your system into a zero residual:

    R = A * x + exp(x) - b
    

    Then take the derivative of R with respect to x:

    dRdx = A + diag(exp(x))
    

    Then iterate. An example is shown below:

    n = 3;
    
    a = rand(n, n);
    b = rand(n, 1);
    
    % solve a * x + exp(x) = b for x
    
    x = zeros(n, 1);
    
    for itr = 1: 10
        x = x - (a + diag(exp(x))) \ (a * x + exp(x) - b);
    end
    

    Of course, you could make this more intelligent by stopping iteration after the residual is small enough.