Scripts Comments: ● Scripts can use variables that were previously defined ● Scripts can modify variable that were previously defined (this might be dangerous!) ● Scripts can call other scripts ● The script must be in a folder which is currently scanned by Matlab.
Functions in MATLAB MATLAB already has a (huge) set of built in functions. Ex >> cos(pi) ans = -1 >> sqrt(4) ans = 2 Info on how to use these functions can be found using the help function. >> help exp ...some stuff... The command help itself will list a broader help menu.
Functions in MATLAB Obviously, we will usually need to create particular functions to solve our problem. There are two important class of functions ● Matlab functions: they're defined in a file and are available as long as the file is present ● Anonymous functions: they're defined “on the fly” and are available until MATLAB is closed
Matlab Functions A Matlab Function is defined in a file with extension “.m”, just like a script. The file name, though, must have the same name of the function. There are a few rules for the function name: ● Cannot match the name of an existing function ● Cannot match the name of an existing Matlab variable ● Cannot match some reserved words/keywords (like for, if, while, try, source, terminal, ...)
Matlab Functions Note: technically, the function name do not need to match the name of the file. In fact, you could have more than one function per file. However, except for the first function, all the other functions are local and cannot be accessed from outside. Golden rule: one function per file, with the name matching the file name.
Matlab Functions Let's suppose we want to create a function that adds two numbers. We'd like to call it ' add' . A call of help, tells us that that function already exists >> help add ...details of the function We can call our function my_add
Matlab Functions This is how the file my_add.m will look like %% This is my add function function z = my_add(x,y) z = x+y;
Matlab Functions Comments: ● The character '%' indicates that whatever follows is a comment. ● The keyword 'function' specifies that we're declaring a function ● After 'function' we specify the name of the output variable. After that, we have an '=' and how the function should be called (including the list of arguments). ● The first block of (contiguous) comment lines will be used by Matlab when the help function is used >> help my_add This is my add function
Matlab Functions In order to use our new function, we must save it in a folder currently scanned by MATLAB or in the current folder. Then, we can use the new function >> my_add(2,3) ans = 5
Matlab Functions We can also create functions with more than one output. Ex: we need to create a function which returns the quotient and the reminder of the division between two numbers. Note: >> help division division not found Therefore, we could call our function division.
Matlab Functions The file division.m would look like %% This function computes the %% quotient and remainder of %% the division n/d function [q,r] = division(n,d) q = floor(n/d); r = n – q*d;
Matlab Functions Comments: ● The function floor is a built in function that returns the largest integer smaller than its argument ● This function would not work if one between n or d is negative though it would if they're both negative (why?) ● The return value is now an array of size 1x2
Matlab Functions We can now call the function >> [q,r] = division(3,2) q = 1 r = 1 Note: if we're interested only in the first output variable, we can simply write >> q = division(5,2) q = 1 If called without specifying what to do with the return values, the first return value will be stored in ans.
Matlab Functions Summarizing: ● Functions look like scripts ● Functions have their own workspace ● Functions inputs/outputs define what variable from outside can be accessed from inside the function, and viceversa ● Useful to add an initial comment for the help
Anonymous Functions Sometimes we need to define a function on the fly, and don't have time to write an m-file and save it (or cannot). If the function can be written in 'one line', then we can use anonymous functions (sometimes called lambda functions ).
Anonymous Functions A lambda function exists only in the workspace, it is not global. Moreover, it does not have a name (it is anonymous). In order to use it, we must have a handle to it. >> f = @(x) (x + sin(x)) f = @(x)(x+sin(x)) >> whos Name Size Bytes Class Attributes f 1x1 32 function_handle
Anonymous Functions Comments: ● f is of type 'function_handle'. It's only use is to be able to call the anonymous function ● the '@' symbol is used to obtain a handle of the following function. It can also be used to get handles of standard Matlab Functions: >> g = @sin; >> g(pi) ans = 1.22416e-16
Anonymous Functions More comments: ● the arguments of the lambda functions are defined inside the first group of parentheses ● the actual expression of the function is defined in the second set of parentheses ● in its expression, the lambda function can use also variables that are visible in the workspace. However, the value of the variable at the time of the function definition will be used (no updates if the global variable changes)
Anonymous Functions Ex: >> a = 1; >> f = @(x) (a + x); >> f(2) ans = 3 >> a = 2; >> f(2) ans = 3
Conditional Statements Logic variables can be used to determine different behaviors of the code. Ex: if (something is true) do this else do that
If statement The most important conditional statement in Matlab is the if statement. The syntax is the following if variable some matlab code end The code inside the if statement will be executed only if variable has value 1 (true).
If statement Note: instead of a variable, we could have an expression. Ex: if a>2 do something end Note that an if statement is always closed with the keyword end.
If statement The function division revised function [q,r] = division(n,d) if d==0 disp('Error! I can''t divide by zero.') return end q = floor(abs(n/d)); r = n – q*d; Note: return tells matlab to conclude the execution of the function.
If-else statement Sometimes we need to switch between two scenarios. Solution A: put all the code for scenario 1 inside an if together with a return statement (like in division.m) Solution B: use if-else statement
If-else statement Ex: create a function that, given two numbers and a char ('+', '-') performs the corresponding arithmetic operation. The function should do different things depending on the input char. The function should also be able to detect an invalid char for the operation selection.
If-else function r=sum_or_diff(x,y,c) % COMMENT HERE if c~='+' && c~='-' 'Error! This function can only add and subtract. Sorry...' return end if c=='+' r = x+y; else r = x-y; end
If-else Comments: ● The comparison operator is == , not = . A single equal sign means assignment , a whole different thing. ● The 'not equal' comparison operator is ~= . Octave also accpets != , but Matlab does not. ● If the condition in the if statement is false, the else statement will be executed. That's why we had to put a return in the initial check. Otherwise, the else would be executed also for invalid inputs. ● An if-else statement can only handle two possible scenarios. If more than two, use...well, wait one more slide.
If-elseif-else statement If we have more than two scenarios, we can use the if-elseif-else statement.With this choice, we could write the function in the previous example as if c=='+' r = x+y; elseif c=='-' r = x-y; else 'Error! Invalid choice for c.' end Much concise and clean: no initial check required. If c has an invalid value, the else statemente will be executed.
If-elseif-elseif-...-else We can have as many elseif as we want in the same block. Ex: write a function that extends the previous one, allowing any possible arithmetic operation ('+','-','*','/') plus the power ('^'). The function should still be able to detect invalid operations.
If-elseif-elseif-...-else function r = operation(x,y,c) % COMMENT HERE if c=='+' r = x+y; elseif c=='-' r = x-y; elseif c=='*' r = x*y; elseif c=='/' r = x/y; elseif c=='^' r = x^y; else 'Error! Invalid choice for c.' end
If-elseif-elseif-...-else Note: inside the block for '/' we could have added a check for non-zero denominator: ... elseif c=='/' if y==0 'Error! Can't divide by zero!' else r = x/y; end elseif c=='^' ...
Switch statement If we have many elseif, the notation is cumbersome. Better to use a switch statement: switch expression case value1 do something case value2 do something ... case valueN do something otherwise do some default stuff end
Switch switch c case '+' r = x+y; case '-' r = x-y; case '*' r = x*y; case '/' r = x/y; case '^' r = x^y; otherwise 'Error! I don''t know that operation. Sorry.' end
Switch Comments: ● A switch is conceptually equivalent to a bunch of elseif. ● From the performance point of view, a switch is more efficient: the computer places (at least it tries to) the different scenarios commands contiguously in memory, increasing jump speed. ● The otherwise at the end is often used to catch invalid arguments. If there are no invalid scenarios, one can use it for 'the most general behavior' ● You can leave a case empty. If that case is selected, matlab will simply...do nothing.
Loops Sometimes we have to do the same operation on many variables. Writing the same code many times is dumb: ● Takes time ● Error prone ● Code not optimized Moreover, sometimes we don't know a priori the number of times the operation has to be performed.
The for loop A for loop consists of some statements that will be executed depending on a control variable. This variable ranges in a well-defined set of values and can be used in the loop . Syntax: for variable = values statement(s) end
The for loop Comments: ● A for loop is always closed with an end (as the if/switch statements) ● The name of the variable is arbitrary. Be aware that if the name matches the name of an existing variable, the existing variable will be overwritten. ● The control variable assume the given values one by one, in the order they are given. ● The control variable can be used for calculations inside the loop. ● The control variable will still be available after the loop. Its value will be the last one used in the loop.
The for loop Ex.: Write a function that computes the factorial of a positive integer number. Def: the factorial of a positive integer number is defined as follows: n! = n*(n-1)*(n-2)*...*3*2*1 Note: 'factorial' already exists in matlab. We'll call the function 'my_factorial'.
The for loop function res = my_factorial(n) %% Comment here if (n<0) disp('Error! N must be positive!); res = 0; return; end
The for loop if (mod(n,1)~=0) disp('Error! N must be an integer!); res = 0; end res = 1; for i=1:n res = res*i; end
The for loop Comments: ● The function mod(x,y) computes the remainder of the division x/y. ● The control variable is i, and it ranges in the array of values [1 2 3 … n]. ● The range need not to be increasing. Another valid solution would be for i=n:-1:1. Notice that, by default, a:b in matlab creates an array of numbers in [a,b] with spacing equal to 1. If we want a different spacing, we must specify it: start:spacing:end
The for loop Note: the values for the control variable may be the result of another function. Ex: for i=compute_first_n_squares(n) root = sqrt(i); if (i~=root) disp('I am bad at math and/or matlab!'); end end
The for loop Summary: ● We can write an operation once and let matlab repeat it many times. ● We can have a range of values not known at the moment when we write the code. ● However, the range of values must be computable beforehand !
Break/Continue Sometimes we want to quit from the loop if something happens, or maybe skip one value. Ex: we want to cycle through [1 2 3 4 5 6 8 9 10]. Idea 1: for i=1:6 do_something end for i=8:10 do_something end
Break/Continue Idea 2: for i=1:10 if i~=7 do_something end end
Break/Continue Idea 3: for i=1:10 if i==7 continue end do_something end
Break/Continue The 3 ideas do exactly the same thing. But: ● Idea 1 is not great if we want to skip many values and/or we have a large block of instructions inside the loop ● Idea 2 is better, but it's not clear that the code will simply skip that value ● Idea 3 clearly states that the value 7 has to be skipped.
Break/Continue The other instruction that breaks the loop pattern is... break . Eg: given a list of (descending) ordered integers, compute the factorial of all of them function res = all_factorials(integers) res = ones(n,1); % Let's initialize everything to 1 for i = 1:n if integers(i)<=1 break; %% All the following must be 1's too end res(i) = my_factorial(integers(i)); end
The while loop To overcome the problem of being able to compute the range of values beforehand, we need a loop that can realize if it is time to stop evaluating a conditional statement Naive idea: for i=1:10000000000000 some_code_here if something_happens break; end end
The while loop Comments: ● It's dumb. ● We still need a range of values large enough so that the loop will end because of the if, not because it reaches the end of the values ● Seriously though, it's dumb.
The while loop A while loop is clearer and shorter. Syntax: while conditional_statement do_some_stuff end
The while loop Comments: ● The rules for the conditional statement are the same as for the if/switch statements. ● The condition inside the statement is sometimes called exit condition. ● A while loop ends with a while, just like for loops. ● Inside a while loop, one can use break/continue, just like inside for loops.
The while loop WARNING!!!! There is NO GUARANTEE that the loop will end. The user MUST make sure that sooner or later the exit condition will be satisfied. Otherwise the code enters a so called infinite loop. Infinite loops are bad (also for your grades...). Safe rule: always include a maximum number of iterations, an iteration counter and a check on the iteration counter.
The while loop Ex: max_iter = 1000; iter = 0; while condition && iter<max_iter iter = iter+1; do_something; end Note: the loop will be executed at most 1000 times. Even if you're sure that the condition will be satisfied eventually, add a maximum number of iteration (perhaps big).
The while loop Ex: write the factorial function using a while loop. f unction res = my_factorial2(n) %Comments here if … %error msg end res = n; i=n; while i>0 res = res*i; i = i-1; end
The while loop Compute the largest power of 2 smaller than a given number. function res = my_integer_log_2(x) if x<0 disp('Error msg') end if x>=1 res = 0; while 2^res<x res = res+1; end else res = -1; while 2^res>x res = res-1; end end
What we know so far... ● Variable types: differences and properties ● Functions: matlab vs anonymous ● Conditionals: different behaviors depending on input values ● Loops: repeat the “same” operation an arbitrary number of times ● Scripts: distributable code
What we can do so far... ● Manipulate tables of numbers (matrices) ● Manipulate strings ● Code somewhat complex algorithms used in applied mathematics
Some examples Statistics. Suppose we have a dataset consisting of a table of numbers in 365 rows and 24 columns. These entries represent the temperature in Atlanta at different times of the day during the whole year. In particular, if T is the name of this table, T(i,j) is the temperature at (j-1) o'clock of day I (hours are in a 24h format).
Statistics Prob 1: how can we compute the average temperature at a particular day? Prob 2: how can we compute the average temperature at a particular time of the day? Prob 3: how can we compute the average temperature in the whole year? Note: look in file temperatures.m
Some examples Sorting. Suppose we have an array of n numbers and we have to sort them. There are many algorithms to do this and matlab has some of them implemented. But we want to implement one of them ourselves. We will implement the least efficient, but hopefully more intuitive.
Sorting Bubble-sort The algorithm does the following: ● Keep scanning the vector, swapping consecutive elements that are in the wrong order. ● If one sweep goes without a single swap happening, then we're done
Bubble-sort Pseudo-code until something happens do loop through the array if the element v_i>v_(i+1) then swap them end loop end do Note: solution in bubblesort.m (& swap.m)
Checking inputs We can tell the user what each argument should be (double, string, array,...). But we can also check, and handle possible errors. Moreover, we can allow the user to pass less input arguments, and use some pre-defined ones for the missing ones.
Checking type For basic types, matlab has function that check if the input variable is of that type. Ex: >> isnumeric(pi) ans = 1 >> ischar('hello') ans = 1 >> isinteger(pi) ans = 0
Checking type Built-in functions are: isnumeric, ischar, isfloat, isinteger, isreal, islogical, isstruct, issparse,... In case we create a new type, we can use isa : >> isa(x,'mytype') ans = 1 Note: if mytype is not defined, matlab simply returns false.
Checking inputs Consider our sort algorithms: ● Orders from smallest to largest. ● Can be extended to both ways ● Smallest to largest is by far the most common use. → Give user the option to call with just one input (the array). This will perform ordering smallest->largest.
Recommend
More recommend