Warm up exercise
Sometime, you need to iterate many times but don't really want to create a vector, or you don't know in advance how many time you need to iterate...for this you can use a while statement.
The syntax for a while statement is
At the beginning of each iteration, Matlab evaluates the expression at the top of the loop. if it is true, Matlab executes the statements to the end. If it is false, Matlab jumps to the end
and continues after it.
So, for example:
>> while x>0
will print out all the numbers from 9 to 0 (including both)
Take note of two things:
Defining your own function
While Matlab has a vast collection of functions, sometimes you want to add some of your own. A function should be thought of as a black box, with a slot in the top (for the input) and a drawer at the bottom for the output. When you give the function input ("call the function"), it calculates the output and puts it in the drawer ("returns it"). Once the function is written, you do not need to care about how it works.
Functions must be defined in their own file, and the name of the file must match the name of the function. So, for example, to define a function called example_function_1, create a file named example_function_1.m. That file must start with the keyword function, so
function y = example_function_1(x)
is the first line of the file. let's dissect this first line:
So the rest of the file could be
admittedly, a very boring function: It takes the input value (locally called x), doubles it, and assigns that result to y. Since y is declared to be the return value and the function has
ended, the return value is simply twice the input.
we call the function by giving it a value:
The return value can then be assigned to another variable:
>> z= example_function_1(18);
An important difference between a function and a script (the files that don't have "function" as their first word are called scripts) is that of "variable scope".
When executing a script from the command-line, the scripts has access to all the variables that are defined on the command line. For instance, if you have a script called script1.m whose contents are
and you run this script from the commandline like so:
>> y = 6
You will see that the script knows that x=2 and that y=6. Not only this, note that y is changed in the scripts, the new value of y, 3 is also the value of y when check on the command
line. This seems natural, perhaps, but this is not how functions behave. A function with the same content function1.m
will fail to run, since within the function there are no such variables x and y. The variables of the function, are different from the variables outside the function, even if they have
the same name.