MATLAB: How to use the fminsearch function to find optimal values corresponding to the least-squared error

fminsearchfunctionleast square errorMATLAB and Simulink Student Suiteoptimal values

Hi,
I have the following data:
x = [10 20 30 40 50 60 70 80 90 100 110 120]';
y = [0.18 0.40 0.65 0.80 0.87 0.92 0.94 0.95 0.96 0.96 0.97]';
Using this function:
y = (x.^n)/((50 + x).^n)
I need to find the optimal values that correspond to the least-squared error by using the fminsearch function.

Best Answer

  • This code works, but your function doesn’t give a good fit:
    x = [10 20 30 40 50 60 70 80 90 100 110 120]';
    y = [ 0 0.18 0.40 0.65 0.80 0.87 0.92 0.94 0.95 0.96 0.96 0.97]';
    yfcn = @(n,x) (x.^n)./((50 + x).^n); % Objective Function
    NRCF = @(n) norm(y - yfcn(n,x)); % Norm Residuals Cost Function
    n0 = 1; % Initial Paramenter Estimate
    est_n = fminsearch(NRCF, n0);
    figure(1)
    plot(x, y)
    hold on
    plot(x, yfcn(est_n,x))
    hold off
    grid
    Also, I added a 0 to ‘y’ to equalise the vector lengths. Check that and substitute the correct value wherever it needs to go in ‘y’ so the vector lengths match.