For
best results paste code fragments into your MATLAB® editor and modify them. Experiment! The best way to learn a language is to “talk.”
We start
our little tutorial with the simplest function possible, a function that does
nothing and save it in a nothing.m file.
function nothing
%
This function does nothing.
It is not
hard to predict what happens when we run this function in MATLAB, … nothing.
>>nothing
>>
Also, in
your Current Directory window in the lower left side, notice that the comment
ended up in the description column (all the way to the right) of this
window. This is a totally
legitimate MATLAB function.
We decided
to do something a little more complicated:
function something
disp('This function can write
something.')
>>something
This
function can write something.
>>
Our
confidence growing after 2 important successes, we now have our function
actually return a value. Notice the assignment statement in the function
definition line, the first line in our examples.
function A = somethingMore
A = 10;
>>somethingMore
ans =
10
The
variable A is local to the function.
So the function did not return the variable A, but only its value, which
is 10. The base MATLAB session,
that we are in when we are looking at the command prompt, doesn’t have a
variable to put the value into. So
it grabs its “default bucket” ans and puts the value 10 in there.
We want to
assign this value to a variable, so we find a suitable variable name that is
descriptive of the variable’s content:
>>nonsense
= somethingMore
nonsense
=
10
Increasing
the level of complexity, we now want our function to return 2 values:
function [A,B] = stillSomethingMore
A=10
B=100;
Notice
that the first assignment statement in the body of the function is not followed
by a semicolon. That means MATLAB
will display its value whenever the function is run. We do not need a semicolon at the end of the function
definition line or behind a for statement.
>>stillSomethingMore
A =
10
ans =
10
As we
would expect, a function first runs through its complete course, all the way to
the end, before it returns its values.
That explains why ans
= shows up at the end.
But what
happened to B? The function
returned the values 10 and 100, but there was only one bucket in our base
MATLAB session to catch those values.
The bucket ans caught the first value, 10, but
the second value, 100, had no place to go.
We have to
set up two buckets to catch both values:
>>[F,G]
= stillSomethingMore
A =
10
F =
10
G =
100
We are
wondering whether we can do something with that variable A, which is supposed
to be local to the function stillSomethingMore, but which MATLAB nevertheless displays in our base session. We are a little bit suspicious, since
even though we ran the function already twice, the variable A still does not
appear as a variable available in our workspace in the upper left window.
We first
create a variable A in our workspace and set it to the value 1,000,000. The variable name now shows up in the
upper left window.
>>A
= 1000000
A =
1000000
>>[F,G]
= stillSomethingMore
A =
10
F =
10
G =
100
Did the
function reset the value of A to 10?
We are about to find out.
>>A
A =
1000000
The only
way we can have the function overwrite a variable in our workspace is if we
assign one of the return values of our function to this variable. The local variable A does absolutely
nothing to our workspace, even if MATLAB displays it because of a missing
semicolon.
>>[A,G]
= stillSomethingMore
A =
10
A =
10
G =
100
Now A
shows up twice, the first time because of a missing semicolon, and the second
time as the first variable of the answer.
It is important to understand that the two A’s are two completely different variables, residing at two completely different memory locations. The first A is local to stillSomethingMore and affects nothing in our workspace, the second A is local to our workspace and affects nothing inside of the function.
The only
way we can have the two totally different variables communicate with each other
is through one of the return values of the function, which we did in this case.
>>A
A =
10
Before we
go to our next step, we reset A in our base workspace to 1,000,000 and make the
A in our function a global variable.
>>A
= 1000000
A =
1000000
function [A,B] = stillSomethingMoreGlobal
global A;
A = 5;
B = 100;
>>[F,G]
= stillSomethingMoreGlobal
F =
5
G =
100
>>A
A =
1000000
Even
though we declared A as a global variable in our function, it still didn’t
affect the A in our workspace. The
A local to our base workspace kept its value 1,000,000.
The value
of a global variable is made available only to those workspaces and functions
that explicitly declare that variable as global. That rule makes a lot of sense. In a program with 15,000 lines of code that several
programmers are working on, one single global declaration could reset all the
variables with the same name in the rest of the program and create one huge
mess.
So, if we
want the variable A in our function and the variable A in our workspace to be
one and the same, we need to declare A as being global in our workspace.
>>global A
Warning:
The value of local variables may have been changed to match the
globals. Future versions of
MATLAB will require that you declare
a variable to be global before you use that variable.
>>A
A =
5
What
happened? MATLAB told us that what
we are trying to do is really a bad idea, but it will let us get away with it
this time. We just shouldn’t do it
again.
Invisibly
to us, the global variable A with the value of 5 it got from the function stillSomethingMoreGlobal was sitting around somewhere in
ether space. The minute we
declared our variable A in our base workspace as global it adopted the same
memory location as the global variable A, and, of course, its current value
5. The 1,000,000 is no more. Note how the class description of A in
the workspace window in the upper left hand corner changed.
What about
our previous function that also used the variable A? It is still a variable local to that function and has
nothing to do with our global variable A.
>>stillSomethingMore
A =
10
ans =
10
>>A
A =
5
Before we
go on, it is important to make one point very clear: the concept of declaring a
variable to be global was introduced only for the student to gain a bird’s eye
perspective of how functions could be used. It is almost never a good idea to declare a variable to be
global.
The beauty
and incredible strength of functions are that they are black boxes. That means, the programmer only has to
know what goes in and what comes out.
What goes on inside is of no concern, which is why the variables inside
of a function are local only to that function and cannot change anything else
in the program.
Think of
it this way: if every driver had to understand how automobiles work, there
would be a lot fewer drivers. If
every programmer had to understand the inside of every function and toolbox he
or she used, there would be a lot fewer programs. That is the beauty of the local variable.
We now
take our function discovery process one step further. We will write a function that accepts an argument:
function Answer = tenTimes(x)
Answer = 10 * x;
>>tenTimes(100)
ans =
1000
That was
easy. What follows isn’t exactly
rocket science either, just a logical extension of what we already learned.
We will
now write our first useful function, a function that helps us answer a question
we are faced with numerous times in our life: What is the total?
function cost = whatsTheTotal(n,p)
cost = n * 10 + p * 1;
Our budget
is $20.- Since notepads are
relatively expensive ($10.00 each) in relationship to pencils which we can buy
just for a buck each, we can only afford 1 notepad and 10 pencils. We make that amply clear to MATLAB:
>>notepads
= 1
notepads
=
1
>>pencils
= 10
pencils
=
10
>>whatsTheTotal(notepads,
pencils)
ans =
20
So far, so
good. Now we reverse the arguments
and MATLAB doesn’t get it anymore that we want 10 pencils and one notepad.
>>whatsTheTotal(pencils,
notepads)
ans =
101
We are
getting really mad now that MATLAB doesn’t understand what we want and decide
to use the same variables that are used inside of function.
>>n=notepads
n =
1
>>p=pencils
p =
10
>>whatsTheTotal(p,n)
ans =
101
To no
avail, MATLAB still doesn’t get it.
What’s being passed along between our base session and the function are
not variables, but values of variables.
In our base session n=1 and p=10. So the values passed to the function are 10, 1 in that
order. That means inside the
function the values of n and p are 10 and 1 respectively.
The n and
p in our function have nothing to do with the n and p in our session.
continue on to recursions