MATLAB Answers

Curve fitting of a custom equation with a predefined value

5 views (last 30 days)
Hi,
in my project i have regular strain and stress values which i want to apply a curve fit according to (y = A + B*x^n) equation. In my code i need to take the 'A' value from a previous calculation(another curve fit). Hence in this new curve fitting operation i want to use this value however, i could not do this neither with curve fitting tool or directly from the code. Can you please offer a solution? Thank you in advance. :)
Here is the part of the code i tried to solve this problem.
%part i calculated the A
[xData, yData] = prepareCurveData( TruePS, Tsts );
findA = fittype( 'poly4' );
opts = fitoptions( 'Method', 'LinearLeastSquares' );
[fitresult, gof] = fit( xData, yData, findA, opts );
h = plot( fitresult,'-.r' );
hold on;
coeff=coeffvalues(fitresult);
A=coeff(5);
%part i am trying to calculate B and n.
findBN = fittype( 'A' + B*x^n , 'independent', 'x', 'dependent', 'y' );
opts = fitoptions( 'Method', 'NonlinearLeastSquares' );
opts.Display = 'Off';
opts.StartPoint = [0.821194040197959 0.0154034376515551];
[findBNresult] = fit( xData, yData, findBN, opts );

  0 Comments

Sign in to comment.

Accepted Answer

Bjorn Gustavsson
Bjorn Gustavsson on 17 Jan 2020
For this type of problems I typically use the basic optimization-functions of matlab - either fminsearch or lsqnonlin depending on type of problem. In my experience that gives me a good solid grasp of what I fit. For the case where you want to fit your function with a subset of parameters I use something like this:
%part i calculated the A
[xData, yData] = prepareCurveData( TruePS, Tsts );
findA = fittype( 'poly4' );
opts = fitoptions( 'Method', 'LinearLeastSquares' );
[fitresult, gof] = fit( xData, yData, findA, opts );
h = plot( fitresult,'-.r' );
hold on;
coeff=coeffvalues(fitresult);
A=coeff(5);
% Modified part
% Define your function to fit to as an anonymous function:
fcn = @(B,n,x) (A + B*x.^n);
% Define a neat function handle where your B and n are taken from "pars"
errfcn = @(pars,x,y,fcn) sum((y-fcn(pars(1),pars(2),x)).^2);
% Your str-guess (I'm guessing about the order of "B" and "n")
par0 = [0.821194040197959 0.0154034376515551];
% then run the parameter fitting:
[pars_optimal] = fminsearch( @(par) errfcn(par,xData, yData), par0);
This "should work". The parameter fitting might be a bit touchy with respect to the initial guess. It might be more efficient to run the fitting with lsqnonlin instead, for that one would have to modify the error-function from calculating the sum-of-squared-residuals to just returning the residuals (without squaring and adding-up).
HTH

  1 Comment

Cagatay Kasar
Cagatay Kasar on 17 Jan 2020
Thank you very much for your answer. Have a nice day. :)

Sign in to comment.

More Answers (0)

Sign in to answer this question.