Hi @彰朗,
Let me address your query regarding, “How can I have the middle data sets during the fitting process by lsqcurvefit?By x = lsqcurvefit(fun,x0,xdata,ydata), x0 is initail data set and x is final data set.I need the middle data sets. if possible, could you let me know how to get the middle data sets? I'd like to make some graphs with middle data sets by fun in order to compare the grapfs differences.I tried multiple lsqcurvefit, which means the below process. But, it needs so many hours.... 1. calculate the x by lsqcurvefit and have the loop number. e.g. loop number = 100 2. set MaxIterations as 10 and calculate the x10 by lsqcurvefit 3. set MaxIterations as 20, 30,,,,100 and calculate the x20, x30,,,x100, respectivelly by lsqcurvefit 4. make the graphs with x10,x20,,,x100 “
Please see my response to your comments below.
To address your question effectively and following provided MATLAB documentation by @Matt J, I implemented the code.
https://www.mathworks.com/help/optim/ug/output-functions.html#mw_rtc_OutputFunctionsForOptimizationToolboxExample_B73D5DFB
Yours goal was to enable to visualize the fitting progression and compare the differences in the graphs generated from these intermediate data sets. So, let me help you understand my code structure below.
Function Definition: The main function fitWithIntermediateData is designed to perform the fitting while capturing intermediate results. It takes four parameters: the model function fun, the initial guess x0, the independent variable data xdata, and the dependent variable data ydata.
History Structure: A structure named history is initialized to store the intermediate parameter values at each iteration. This is crucial for later analysis and visualization.
Options for lsqcurvefit: The optimoptions function is used to set various options for the lsqcurvefit function. Notably, the OutputFcn option is set to a custom function outfun, which is called at each iteration of the optimization process. This function is responsible for storing the current parameter estimates.
Output Function: The outfun function checks the state of the optimization. If the state is 'iter', it appends the current parameter estimates to the history.x array. This allows you to track how the parameters evolve over iterations.
Model Function: The yourModelFunction is a placeholder for the actual model you wish to fit. In this example, it is a simple linear function, but you can replace it with any model that suits your data.
Final Fit and Plotting: After the fitting process, the final parameters and the history of intermediate results are available. The code then plots each intermediate fit along with the final fit, allowing for visual comparison.
Here is the complete code with explanations embedded:
function [xsol, history] = fitWithIntermediateData(fun, x0, xdata, ydata) % Initialize history structure to store intermediate results history.x = [];
% Define options for lsqcurvefit options = optimoptions('lsqcurvefit', ... 'OutputFcn', @(x, optimValues, state) outfun(x, optimValues, state, history), ... 'StepTolerance', 1e-6, ... % Adjust step tolerance 'TolFun', 1e-6, ... % Tolerance on the function value 'MaxIter', 1000); % Maximum number of iterations
% Call lsqcurvefit [xsol, resnorm, residual, exitflag, output] = lsqcurvefit(fun, x0, xdata, ydata, [], [], options);
% Display final results fprintf('Final Parameters: %s\n', mat2str(xsol)); fprintf('Residual Norm: %.4f\n', resnorm); fprintf('Exit Flag: %d\n', exitflag); fprintf('Output: %s\n', output.message); end
function stop = outfun(x, optimValues, state, history) stop = false; % Allows optimization to continue
if strcmp(state, 'iter') % Store current x in history history.x = [history.x; x]; % Append current parameters to history end end
function y = yourModelFunction(params, xdata) % Define your model function here y = params(1) * xdata + params(2) + params(3); end
% Define initial guess values as needed initialGuess = [1, 2, 3];
% Define generic data for xdata and ydata xdata = linspace(0, 10, 100); ydata = 2 * xdata + 1 + randn(size(xdata));
[xFinal, fitHistory] = fitWithIntermediateData(@yourModelFunction, initialGuess, xdata, ydata);
% Accessing intermediate results: intermediateResults = fitHistory.x;
% Plotting the results figure; hold on; for i = 1:size(intermediateResults, 1) plot(xdata, yourModelFunction(intermediateResults(i,:), xdata), 'DisplayName', ['Iteration ' num2str(i)]); end
% Plot the final fit plot(xdata, yourModelFunction(xFinal, xdata), 'k--', 'DisplayName', 'Final Fit', 'LineWidth', 2); legend show; title('Intermediate Fit Results and Final Fit'); xlabel('X Data'); ylabel('Y Data'); hold off;
Since you are interested in visualization part of code let me explain the code loops through the intermediateResults array, plotting each set of parameters against the xdata. This will allow you to visualize how the model evolves with each iteration. The final fit is plotted as a dashed line for clear distinction.
Please see attached.
Results
Plot
So, by utilizing the provided code structure, you can capture and visualize the intermediate data sets during the fitting process with lsqcurvefit. This approach not only saves time compared to running multiple fitting processes but also provides a comprehensive view of how the fitting progresses. You can further customize the model function and the plotting sections of code to suit your specific needs. Please let me know if you have any further questions.