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

조회 수: 10(최근 30일)
Michael Hasson 25 Oct 2020
답변: Star Strider 26 Oct 2020
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 25 Oct 2020
I suggest that you use the debugger.
Alan Weiss
MATLAB mathematical toolbox documentation

#### 댓글 수: 1

Michael Hasson 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.

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

Star Strider 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.

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

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by