APPLIED MATH MATLAB 1 What does the fminsearch do and how w
APPLIED MATH - MATLAB
1) What does the fminsearch do and how would you use it to minimize a given function?
2) How do you use fminsearch to fit an arbitrary formula to data (ex. writing a function that computes the least-sqare error between a formula and a given set of data?)
Solution
fminsearch is the function that helps in finding the minimum of scalar function of severable variable by starting it with an initial estimate of the solution and then iterate the solution for multiple steps in order to get the optimal solution
we use it in the function by calling the inbuilt matlab function
Various syntax available in matlab
x = fminsearch(fun,x0)
x = fminsearch(fun,x0,options)
x = fminsearch(problem)
2) Posting an example used in my class for function fitting
function fitting
[x y] = generate_data;
param_guess=[5 0.5 50];
[bestparam min]=fminsearch(@merit,param_guess,[],x,y);
yfit=fun(bestparam,x);
plot(x,yfit,\'r\',\'LineWidth\',2);
hold off
figure(gcf);
title(sprintf(
\'a= %5.3f, b= %5.3f, c= %5.3f, Residuals=%5.3f\'
,bestparam,min ))
ylabel(\'Y\'); xlabel(\'X\');
grid on;
function
sumsquares=merit(param, X,Y)
DIFF = fun(param,X)-Y;
SQ_DIFF = DIFF.^2;
sumsquares = sum(SQ_DIFF);
end
function
Y=fun(coeff,X)
a = coeff(1);
b = coeff(2);
c = coeff(3);
Y= a*X+b*sin(X)+c;
end
function
[x y]=generate_data
x=1:0.2:15;
a=0.9; b=1.5; c=20;
err_p=0.01;
y=fun([a b c], x)+err_p*randn(1,numel(x)).*fun([a b c], x);
end

