Lecture 5Warm up exercise
F(1)=1 F(2)=1 for n>2 F(n)=F(n1)+F(n2)
while StatementsSometime, 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 while expression a bunch of statements end 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:
>> x=10; >> while x>0 x=x1 end >>
will print out all the numbers from 9 to 0 (including both)
Take note of two things:
Exercises
Defining your own functionWhile 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
y=2*x; end
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:
>> example_function_1(17)
or
>> example_function_1(rand)
The return value can then be assigned to another variable:
>> z= example_function_1(18); >> z
Variable ScopeAn 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 commandline, 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 x+1 y=y/2 and you run this script from the commandline like so: >> x=2 >> y = 6 >> script1 >> y 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 function function1 x+1 y=y/2 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.
