Search code examples
matlablinear-regression

MATLAB non-linear regression using cost function


Currently, I am trying to figure out how to solve a non-linear system using a model. The model is:

m2(x) = a*x + 2*exp(b*x)

I have to solve for a and b using the data:

x = [0.00,0.25,0.50,0.75,1.00];
y = [2.10,3.70,6.26,10.03,16.31];

Using that I solve the following cost function:

(a,b) = sum(y(i) - m2(x(i))^2

I have been trying for a while now and I can't figure out how to extract a and b from m2(x(i)). fsolve has not worked for me, I have also tried the routine solve function. I am not looking for an answer but I am looking for a direction to take as I am at a complete roadblock.

Edit: The model captures the dependence of y on the independent variable x I ran this function to get the 5 equations.

function [f] = func(x,y)
    syms a b
    f = a*x + 2 * exp(b*x) == y;
end

With the driver:

for i = 1:5
    f(i) = func(x(i),y(i));
end
disp(f');

Solution

  • your unknowns are a,b so I parametrized them as w in the model, instead of what you did. I used lsqnonlin and solved as follows:

    x = [0.00,0.25,0.50,0.75,1.00];
    y = [2.10,3.70,6.26,10.03,16.31];
    m2 = @(w) w(1)*x + 2*exp(w(2)*x);
    
    
    cost_func = @(w) m2(w)-y; 
    v = lsqnonlin(cost_func,[1 1]); % normal least squares
    plot(x,y,'x',x,m2(v));