where its @ - I got two turntables and a microphone

| categories: basic matlab | View Comments

where its @ - I got two turntables and a microphone

where its @ - I got two turntables and a microphone

John Kitchin

Contents

Introduction

matlab allows you to define inline functions, known as function handles. These are helpful for making small functions that can be used with quad, fzero and the ode solvers without having to formally define function code blocks. One advantage of function handles is they can "see" all the variables in the script, so you don't have to copy the variables all over the place.

the syntax is: f = @(variables) expression-using-the-variables

then f(argument) is evaluated using the expression.

Here are some examples

make a function f(x) = 1/x^2

use dot operators to make the function vectorized. you should in general use the dot operators so your functions work with vectors, unless of course, your function uses linear algebra.

f = @(x) 1./x.^2;
f(2) % should equal 0.25
f([1 2 3]) % should equal [1 0.25 0.111]
ans =

    0.2500


ans =

    1.0000    0.2500    0.1111

you can have more than one variable, e.g. f(x,y)=x*y

f2 = @(x,y) x.*y;
f2(2,3) % should equal 6
f2([2 3],[3,4]) %should equal [6 12]
ans =

     6


ans =

     6    12

using function handles with quad

compute the integral of x^2 from 0 to 2

f3 = @(x) x.^3;
quad(f3,0,2) %the answer is 4
ans =

     4

using function handles with fzero

solve the equation x^2=9.5

myfunc = @(x) 9.5-x^2;
xguess = 3;
fzero(myfunc,xguess)
ans =

    3.0822

using function handles with ode45

solve y' = k*t over the time interval t=0 to 10, y(0)=3

k = 2.2;
myode = @(t,y) k*t;  % myode is a function handle
y0 = 3; tspan = [0 10];
[t,y] = ode45(myode,tspan,y0); % no @ on myode here because it is already
                               % a function handle
plot(t,y)
xlabel('Time')
ylabel('y')

% it is also possible to do coupled odes by defining anonymous functions,
% although not recommended! It's just harder to read than the functions.
%
%  solve
%
%  dX/dW = kp/Fao*(1-X)/(1+eps*X)*y
%  dy/dW = -alpha*(1+eps*X)/2/y
%  X(0) = 0, y(0)=1
%  we will let X = Y(1), y = Y(2)
eps = -0.15;
kp = 0.0266;
Fao = 1.08;
alpha = 0.0166;

myode2 = @(W,Y) [kp/Fao*(1-Y(1))./(1+eps*Y(1))*Y(2);
                 -alpha*(1+eps*Y(1))./(2*Y(2))];
[W,Y] = ode45(myode2,[0 60],[0 1]);
plot(W,Y(:,1),W,Y(:,2))
% even though you can do it, that doesn't mean it is easier to read! And
% shame on me for not labeling the plot axes.
'done'

% categories: Basic matlab
ans =

done

blog comments powered by Disqus