fit a function to a line in matlab

You can fit a function to a line in MATLAB using the "lsqcurvefit" function or the "polyfit" function.

  1. Using lsqcurvefit:

    main.m
    % Define your function
    fun = @(x, xdata) x(1)*xdata + x(2);
    
    % Generate some data points
    xdata = [1 2 3 4 5];
    ydata = [3.1 6.9 10.2 13.5 16.7];
    
    % Initial guess for the parameters of the function
    x0 = [0.1 0.1];
    
    % Fit the function to the data
    x = lsqcurvefit(fun, x0, xdata, ydata);
    
    % Plot the data points
    scatter(xdata, ydata)
    hold on
    
    % Plot the fitted line
    xfit = linspace(min(xdata), max(xdata), 100);
    yfit = fun(x, xfit);
    plot(xfit, yfit)
    
    % Add labels and legend
    xlabel('x')
    ylabel('y')
    legend('Data points', 'Fitted Line')
    
    532 chars
    27 lines
  2. Using polyfit:

    main.m
    % Generate some data points
    xdata = [1 2 3 4 5];
    ydata = [3.1 6.9 10.2 13.5 16.7];
    
    % Fit a line (degree 1 polynomial) to the data
    coeffs = polyfit(xdata, ydata, 1);
    
    % Generate the x values for the fitted line
    xfit = linspace(min(xdata), max(xdata), 100);
    
    % Evaluate the fitted line at the x values
    yfit = polyval(coeffs, xfit);
    
    % Plot the data points
    scatter(xdata, ydata)
    hold on
    
    % Plot the fitted line
    plot(xfit, yfit)
    
    % Add labels and legend
    xlabel('x')
    ylabel('y')
    legend('Data points', 'Fitted Line')
    
    512 chars
    25 lines

Both methods will fit a line (in the form y = ax + b) to the given data points.

gistlibby LogSnag