clc; clear All; %To search for the minimum of an arbitrary function, MATLAB pro- MATLAB provides the function fminsearch. %To use it, you have to write an additional short function calculating the value of the function to be minimized. %If you would want,e. g., to ?t a Lorentzian y = a1/((x - a2)^2 + a3) to a data set Xi, Yi, %you should define in MATLAB a function resulting in the sum of the squared residuals %function d = devsum(a) %global X Y %The start values for the parameters (a1, a2, a3) could of course be chosen in a better way when the data set is known. %An example for the ?t with a Lorentzian is shown in Fig. 2, the data set there was de?ned by % a(1)=20, a(2)=20, a(3)=0.08 X = linspace(0,100,200); Y = 20./((X-30).^2+20)+0.08*randn(size(X)); plot(X',Y','.') hold on; %This function is then used in a call to fminsearch as the first parameter % In physics, a three-parameter Lorentzian function is often used, as follows: % f(x;x0,?,I) = I/(1 + ( (x-x0)/? )^2) % I: is the height of the peak. % x0: is the location paremeter, specifying the location of the peak. % ?: is the scale parameter which specifies the half-width at half-maximum (HWHM). % ? is also equal to half the interquartile range and is sometimes called the probable error. % a(1)= I; height of the peak. % a(2)= x0; location of the peak. % a(3)= ?; half-width at half-maximum (HWHM). a1 = max(Y)*a3; a2 = (max(X)+min(X))/2; a3 = ((max(X)-min(X))/10)^2; a0 = [a1,a2,a3]; %afinal = fminsearch(@devsum,a0); %afinal %a0 opts = optimset('TolX',1e-4,'MaxFunEvals',10000,'MaxIter',10000,'Display','on'); [fitpara,fval,flag,err] = fminsearch(@devsum,a0,opts,X,Y); fitpara %fval %flag %err %opts y_fit = fitpara(1)./((X-fitpara(2)).^2+fitpara(3)); plot(X',y_fit','r') %The function fminsearch can be tuned by additional options, one can demand a certain accuracy, restrict the number of optimization steps etc. %For a detailed description consult Help