L39_Anonymous_functions

advertisement
Anonymous functions, fsolve and
fminsearch

Will not be on the finals
Anonymous function
>> func=@(x)(x^2-4*x+3);
 Gives you a function that takes as an
input a variable x and returns x^2-4*x+3
 Try
>>func(3)

Try
>>ezplot(func)
Two Variable Anonymous function
>>func=@(x,y)(x*y);
 Creates a function that takes as input two
variables and returns their product
 Try
>>func(1,2)
>>func(5,0)

Try
>>ezsurf(func)
fsolve(F,guessval)

Solves a problem specified by
◦ F(x) = 0
◦ for x, where x is a vector and F(x) is a function
that returns a vector value.
>> func=@(x)(x^2-4*x+3);
>> xval=fsolve(func,5)
>> func(xval)
fminsearch(F, guessval)

Find minimum of unconstrained
multivariable function using derivativefree method
>> func=@(x)(x^2-4*x+3);
>> xval=fminsearch(func,5)
>> func(xval)
How to find the best fit line?

Assume that the line y=mx+c is represented as a
two element vector [m c].

Write a function line_fit_error that
◦ Given a line L in the above form and a set of points P
◦ Returns the sum of squared distance of each point in P
from the line L

Distance of the point (xi,yi) from L is given by
𝑦𝑖 − 𝑚 ∗ 𝑥𝑖 − 𝑐
1 + 𝑚2
function val=line_fit(l,p)
% Compute distances
dists=(p(:,2)-l(1)*p(:,1)-l(2))/sqrt(1+l(1)^2);
% Compute sum of squared distances
val=sum(dists.^2);
% Plot the line
h=get(gcf,'UserData');
if (h ~= 0)
delete(h)
end
xmax=max(p(:,1));
xmin=min(p(:,1));
h=plot([xmin xmax],l(1)*[xmin xmax]+l(2),'r');
set(gcf,'UserData',h);
drawnow;
end
Use fminsearch to find the line that
minimizes the fitting error
% Get input points graphically
[x,y]=ginput;
% Create a function that takes as input
% a line and returns the fit error
func=@(l)(line_fit(l,[x y]));
% Plot the points
plot(x,y,'.');
hold on;
axis equal;
axis manual;
set(gcf,'UserData',0);
% Find the line that minimizes the fit error
l=fminsearch(func,[sum(y)/sum(x) 0]);
Download