Error when using fminsearch to find least squares fit of data using a given equation
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (2)
Star Strider
el 26 de Oct. de 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.
0 comentarios
Ver también
Categorías
Más información sobre Solver Outputs and Iterative Display en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!