Error when using fminsearch to find least squares fit of data using a given equation

12 views (last 30 days)
I have a dataset and a nonlinear equation that should fit it. The goal is to minimize the least squares error using fminsearch. I've gotten this code to work with a simple equation (just finding one variable) but can't make it work when the output is a vector. The data 'lag' and 'vario' are both 20-element vectors. The code I'm working with is below. When I run it, I get an error saying "unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is 1-by-20." I've been trying to figure this out for ages -- any thoughts? I'm a super beginner at this, so if the answer is obvious I apologize in advance!
ypred = zeros(1,length(lag));
for k = 1:length(lag)
if lag(k)<m(1)
ypred(k) = m(2)*(1.5*(lag(k)/m(1))-0.5*(lag(k)/m(1)).^3);
else
ypred(k) = m(2);
end
end
yerr = (vario-ypred);
yerr = sum(yerr.^2);
end
m = fminsearch(@(m) varerr(m,lag,vario),[2 2]);
plot(lag, varerr(m, lag, vario)); shg

Answers (2)

Alan Weiss
Alan Weiss on 25 Oct 2020
I suggest that you use the debugger.
Alan Weiss
MATLAB mathematical toolbox documentation
  1 Comment
Michael Hasson
Michael Hasson on 26 Oct 2020
So when I do that, it takes me to line 200 of the actual fminsearch.m file, at which point it's using a variable "fv" that's defined within the fminsearch function. So I guess I'm not sure how to think about debugging when the issue is within the function I'm calling, if that makes sense.

Sign in to comment.


Star Strider
Star Strider on 26 Oct 2020
I can’t figure out from your code what your independent and dependent variables are.
As a general rule, the argument to fminsearch for data-fitting problems is:
objfcn = @(b,x) ...; % Model
fitfcn = @(b) norm(y - objfcn(b,x)); % Returns Norm Of Residuals
[B,resnrm] = fminsearch(fitfcn, [2 2]) % Estimate Parameters
ypred = objfcn(B,x); % Calculate Fit
figure
plot(x, y, 'p')
hold on
plot(x, ypred, '-r')
hold off
grid
Here, ‘x’ are the independent variables, ‘y’ are the dependent variables, and ‘b’ is the parameter vector.

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!