Matlab functions
Understand the concept (independent) variable and current value:
>> x=3
Understand the concept dependent variable:
>> y=2*x
A common name for a generic function/expression depending on x is f(x).
But specific functions should be given specific names, preferably
indicating what the function is doing. For example, sqrt(x) is the matlab
function that computes the (positive) solution y of the equation y^2=x:
>> x=9; sqrt(x)
or just
>> sqrt(9)
We now create a (very trival) matlab function, that just multiplies a given x by 2, as in y=2*x above. We give this function the intelligent name twice(x).
We define the function in a Matlab function m-file with the name twice.m.
We thus create (with >> edit in Matlab) a file with the following content
function y=twice(x)
% This function computes and returns 2x for any given x.
y=2*x;
and give the file (with Save as ..) the name twice.m.
Comments:
1. The file must start with the key word function,
here followed by y=twice(x), where x is the (independent) input
variable, y is the (dependent) output variable, and twice is the name
of your function.
2. On the following line(s) you should write some text that explains
what the function is doing. This text is displayed if you type help
twice
at your matlab prompt. You then get useful info about the function
without actually using it. Try this!
When you use the function in a matlab computation, all text following
%
is ignored.
3. You may put in extra lines and blanks to get better readability if
you like.
Now test by
>> help twice
The info text This function .. should then be
displayed.
Then
>> twice(7)
which should result in ans=14, or
>> y=twice(8)
which should result in y=16, or
>> x=8; y=twice(x)
which should result the same.
============================
Functions of more than one variable:
Write a matlab function that computes the area of a triangle with base
b and height h, of the form
function a = triangle_area(base, height)
% comments
a = .. (for you to complete!)
saved under the name triangle_area.m. Test with
>> a = triangle_area(3,7)
Write a matlab function that computes the resulting capital c of a given
initial investment c0, a given annual interest rate r, and after a given number
of years n.
Find another example of a function of more than one variable to
implement and test.
=====================================
Functions with more than one output argument:
Define a function that computes both the difference and the ratio of
a=1+2+3+..+N and b=N^2/2, of the form
function [difference, ratio] = Leibschnizel(N)
% comments
a = sum(1:N);
b = N^2 / 2;
difference = ..
Note that the output variables appear in a (comma separated)
list/vector.
Note also that we surpress output from within the function by ending
the assignments by ;. The default output is then just the resulting
values of the output variables, here difference and
ratio.
Note also that if at the matlab prompt you type just Leibschnizel(N), you only get the first output variable of Leibschnizel, that is the difference variable, and it will be put in the answer "box". To get both output variables you must specify two "boxes" in the matlab workspace for the Leibschnizel function to deliver the result, like [d, r]=Leibschnizel(N). Now Leibschnizel will put its first output variable in d and its second in r. Test!
Extend your matlab function for capitalists above, so that it computes
and returns/outputs both the resulting capital c and the capital
growth factor c/c0.
Find another example with more than one output value. Implement and
test!
===============
Vector input/output:
The input/output arguments of a function can also be
lists/vectors. For example, write a matlab function that computes the
annual cost for news papers, mowies and cd's, respectively, and also
the corresponding total cost. Hint: use two input list/vector
variables, one for the number of articles, and one for the
corresponding current price per item, and two output variables aswell,
one list/vector with the resulting annual price for each category, and
one scalar (list with just one element) for the total cost, of the
following form, with input arguments n=[n1 n2 n3] and p=[p1 p2 p3],
where
n1 is the number of news papers you plan to buy, and p1 the expected
price per new paper, ets.
function [annual_costs, total_cost]=budget(n,p)
% comments
annual_costs=.. (see Matlab intro I for the .* multiplication)
total_cost=..
Set up a budget using your new tool!!
Change your matlab function for capitalists above, so that instead of
the final capital it computes and returns a list c=[c0 c1 c2 .. cn] of
the capital after each year up to n, that is after 0, 1, 2,.., n
years.
Use the resulting output to visualise your
capitalistic dreams using plot(y,c) with y=0:n and c your
capital list/vector returned by your matlab function.
=======================
Composite functions in Matlab:
In addition to your twice.m matlab function, write another one
square_and_add_1_to.m that squares a given input argument and then adds one. Then
consider the composite functions
twice(square_and_add_1_to(3)) and square_and_add_1_to(twice(3)). Do they yield the same result? Should they?
==========================
Functions calling another functions:
One may also call another function from within a given function. Test
the following example:
function y=MultiDouble(x,N)
% comments (describe what this function is doing)
for i=1:N
y(i)=twice(x(i));
end
A function that is used only for some specific purpose, and not of
common interest, can also be put in the same file as a calling
function. For example, the twice function could be put in the
MultiDouble.m file as follows:
function y=MultiDouble(x,N)
% comments (describe what this function is doing)
for i=1:N
y(i)=twice(x(i));
end
function y=twice(x)
% comment
y=2*x;
Remove your previous twice.m file and test this construction. Note
that if you later call twice directly from your matlab prompt, you
cannot expect matlab to find the function twice because it is now
hidden
in a file with another name!
Let us also remark that of course this can be done more easily
by just writing y=2*x directly at the matlab prompt!
Exercise Write a matlab function that computes n!=1x2x3x..xn
for a given n, and another one, that uses this one, that computes
the binomial coefficient n!/(n-k)!/k! for given n and k.
==========================
feval
To be able to implement "functions of function", like the function
giving the integral of given functions or the function find the zeros
of given functions, it is convenient to have a function that can evaluate
a given function for given argument values, that is, that can take
both a function name and its argument values as input, and delivers
the corresponding function value as output.
This is exactly what matlabs built-in function feval does, with syntax as follows: feval('func', args), where func is the name of the function to be
evaluated, and args is the arguments for which the function should be
evaluated. For example, to get the value of the function twice for x=3
one writes feval('twice',3), or to get the value of the trangle area of
a triangle with base 2 and height 5 one writes feval('trangle_area',2,5).
See help feval !