Scripted general fitting data: Error in fminsearch
조회 수: 2 (최근 30일)
이전 댓글 표시
I am very new in Matlab. And I am still going through the text book.
And here is a piece of code I tried to fit the exist data.fil. It is a 5*2 data.
%loading data
load data.fil; x=data (: ,1 ); y = data (: ,2);
%plotting
xmin = min(x); xmax = max(x); npts = 1001;
dx = (xmax - xmin) / (npts -1); xplot = xmin:dx:xmax;
%set ifit to 0 and don't continue on to the fit until the user sets it to 1
ifit = 0;
while (ifit == 0)
disp ('Enter an initial guess for the function')
a = input ('parameters [a1, a2,...] in vector form [...]-');
%plot data and the initial function guess
yplot = funcfit (a, xplot);
plot (x,y, 'b*', xplot, yplot, 'r-');
xlabel ('x');
ylabel ('y');
title ('Initial Guess and Data')
ifit = input ('0: guess again; 1: fit with this guess - ');
end
% Define the option TolX set; look for the best parameters to minimize the leastsq.m function
option = optimset ('TolX', 1e-4);
a = fminsearch (@leastsq, a, option, x, y);
% evaluate the function with the final fit parameters
yplot = funcfit (a, xplot);
% plot
plot (x,y, 'b*', xplot, yplot, 'r-');
xlabel ('x')
ylabel ('y')
title ('Final fit and data')
And here are the functions being called: funcfit.m
% fitting function, find a1, a2 to fit the fuction f represents
function f = funcfit(a,x)
f= a(1).*exp(a(2).*x);
leastsq.m
%the square of minimum between the y in the data:fil and fiting
function s=leastsq(a,x,y)
s = sum ((y - funcfit (a,x).^2);
So when I run the script, I got
Enter an initial guess for the function
parameters [a1, a2,...] in vector form [...]-
I tried [1,1], and it fits.
0: guess again; 1: fit with this guess -
So I input 1. The it shows below:
Attempt to execute SCRIPT fminsearch as a function:
M:\pc\Desktop\Matlab start\fminsearchfitting\fminsearch.m
Error in fminsearch (line 51)
a = fminsearch (@leastsq, a, option, x, y);
I have checked many times, and I do not know where it is wrong. I learnt fminsearch only process scalar. How do I do?
Many thanks.
댓글 수: 0
답변 (1개)
Star Strider
2014년 5월 16일
You may have named your script file (or some other script in your user directory) as ‘fminsearch’.
Type this line in the Command Window:
which fminsearch -all
On my computer (Windows 8 64), I get one result:
C:\Program Files\MATLAB\R2014a\toolbox\matlab\optimfun\fminsearch.m
If you get more than that, especially if one is your script file, rename your script file.
댓글 수: 2
Star Strider
2014년 5월 16일
I see the problem.
Change:
a = fminsearch (@leastsq, a, option, x, y);
to:
a = fminsearch (@(a) @leastsq(a, x, y), a);
I didn’t run your code so I don’t know if that’s the only problem, but it should at least not throw the error now.
참고 항목
카테고리
Help Center 및 File Exchange에서 Title에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!