Warning: Unable to solve symbolically. Returning a numeric solution using vpasolve.
Hi Yang Hu,
As per my understanding you wish to fit a each column of x with given y and determine the S and P parameters along with goodness of fit for each column in the attached table. Here, I am assuming the metrics for goodness of fit is R^2 value.
You can use lsqcurvefit function for this task. It is based on least square method. It adjusts the parameters of a given model to best fit a set of data points by minimizing the sum of the squares of the residuals. Please refer to the documentation to learn more about lsqcurvefit function : https://www.mathworks.com/help/optim/ug/lsqcurvefit.html
Please refer to the steps in following code snippet to learn how lsqcurvefit can be used:
% Load the data
x_input = readmatrix('IndiMSD.xlsx');
x = x_input(2:end, :); % Discard the first row
y = (15:15:1440)'; % Make sure y is a column vector
% Preallocate
numCols = size(x, 2);
S_values = zeros(1, numCols); % S parameter
P_values = zeros(1, numCols); % P parameter
gof_values = zeros(1, numCols); % goodness of fit
% Custom equation as a function handle
customEquation = @(params, x) 2 * ((params(1)^2) * (params(2)^2)) * ((x./params(2)) - 1 + exp(-(x./params(2))));
% Define the options for lsqcurvefit
options = optimset('Display', 'off');
% Loop through each column of x
for col = 1:numCols
x_col = x(:, col);
% Initial guess for parameters [S, P], please modify this as per your
% requirement
initialGuess = [1, 1];
% Perform the curve fitting
[fittedParams, ~, ~, exitflag, output] = lsqcurvefit(customEquation, initialGuess, x_col, y, [], [], options);
% Store the fitted parameters
S_values(col) = fittedParams(1);
P_values(col) = fittedParams(2);
% Calculate goodness of fit (e.g., R-squared)
y_fit = customEquation(fittedParams, x_col);
SS_res = sum((y - y_fit).^2);
SS_tot = sum((y - mean(y)).^2);
gof_values(col) = 1 - (SS_res / SS_tot);
end
% Display Results
% disp('Fitted S:'); disp(S_values);
% disp('Fitted P:'); disp(P_values);
% disp('Goodness of fit (R-squared):'); disp(gof_values);
Hope this helps!