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

조회 수: 12 (최근 30일)
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

답변 (2개)

Alan Weiss
Alan Weiss 2020년 10월 25일
I suggest that you use the debugger.
Alan Weiss
MATLAB mathematical toolbox documentation
  댓글 수: 1
Michael Hasson
Michael Hasson 2020년 10월 26일
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.

댓글을 달려면 로그인하십시오.


Star Strider
Star Strider 2020년 10월 26일
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.

카테고리

Help CenterFile Exchange에서 Solver Outputs and Iterative Display에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by