Selected Programming Languages MATLAB Instructor: Luca Bertagna - - PowerPoint PPT Presentation
Selected Programming Languages MATLAB Instructor: Luca Bertagna - - PowerPoint PPT Presentation
Selected Programming Languages MATLAB Instructor: Luca Bertagna Lectures: Tu 11:30am-12:20pm MSC W304 Labs: Th 11:30am-12:20pm MSC E308A Office: N422 Office hours: Tu 10:30am-11:30am Th 3:00pm-4:00pm Selected Programming Languages MATLAB
Selected Programming Languages MATLAB
MATLAB stands for “MATrix LABoratory”. It was first developed to allow students to handle matrices without having to deal with lower level languages (C, Fortran). Through the years, it got quite more complex and powerful.
Key features:
- High level language
- Interactive environment
- Multi-paradigm
- Built in functions for linear algebra, statistics,
- ptimization, ordinary differential equations, etc.
- Built in graphics for data visualization
- Tools for interfacing with external languages,
such as C++ and Java
- Supports parallel computing
- And much more
What is a programming language?
Quoting the almighty wikipedia: “A programming language is an artificial language designed to communicate instructions to a machine, particularly a
- computer. Programming languages can be used to create
programs that control the behavior of a machine and/or to express algorithms.” Ex: C, C++, Fortran, Java, Python. Note: HTML is NOT a programming language.
MATLAB programming paradigms
- Imperative: the programmer specifies statements that
modify the program state.
- Procedural: the program is made of “procedures” (or sub-
routines). Each sub-routine does a specific job and can call other procedures.
- Object oriented: each variable in the program is an
“object”, which features particular “attributes” (inner variables) and “methods” (inner functions). Interactions with other objects depend on their “interface”.
Variables in MATLAB
- double: stores a number
- char: stores a character
- cell: stores a list of (possibly heterogeneous)
variables
- function handler: stores a handler to a function
- struct: encapsulate other variables as fields
- ...
Variables in MATLAB
Variables types in MATLAB are implicitly detected. Ex: >> a = 3; <-- Here a is a double >> a = 'Hello world!'; <-- a is now a char >> a = {1,2}; <-- a is now a cell >> a = @(x)(x^2); <-- a is now a function handler
Variables in MATLAB
Variable types can be changed on the fly. Ex: >> s = 'hello'; >> s = s + 1; >> s ans = 105 102 109 109 112 What happened? MATLAB converted each character in 'hello' into its corresponding ASCII integer, then added 1 to each of those integer.
Variables in MATLAB
At any point, you can get a list of the variables in your workspace by typing whos: >> a = 1; >> b = 'hello'; >> whos Name Size Bytes Class Attributes a 1x1 8 double b 1x5 5 char
Variables in MATLAB
For each variable, whos gives five informations:
- Name: can contain letters, numbers and '_'. Can't
start with a number
- Size: the length of the array/cell
- Bytes: the size in memory
- Class: the type of the variable
- Attributes: other attributes (complex, global, etc.)
Variables in MATLAB
MATLAB has some built in variables, like
- pi <-- it's 3.1415...
- i <-- it's the square root of -1
- j <-- same as i
- eps <-- it's roughly 2.22e-16
Variables in MATLAB
There's also the variable ans, which stores the result of the last calculation, unless this was followed by ';' or the result had already been stored inside another variable Ex: >> 2+1 ans = 3 >> whos Name Size Bytes Class Attributes ans 1x1 8 double
Arrays in MATLAB
Note: each variable in MATLAB is actually an array. An array is simply an arrangement of elements
- f the same type.
Ex: a = [1 2 3 4] is an array of numbers b = 'hello world!' is an array of characters
Arrays in MATLAB
Arrays can be multi-dimensional. For instance, a 2D array can be seen as a table of elements, ordered in rows and columns. Ex: A = [1 2 3 4 5 6 7 8] is a 2D array of numbers of size 2x4 Notes:
- usually, a 1D array is simply called array.
- an array of characters is usually called string.
- a 2D array of numbers is usually called matrix.
- By default, MATLAB interpret a variable as a 1x1 2D array
Arrays in MATLAB
When dealing with arrays, it's useful to be able to find their size/dimension. This can be done with the command size: >> s = 'hello world!'; >> size(s) ans = 1 12 The output tells us that s is an array with 1 row and 12
- columns. If the array has dimension D, then size returns a
1xD array, where the i-th entry represents the size of the array along the i-th dimension.
Arrays in MATLAB
In order to access the elements of an array we can use the operator (): Ex: >> a = [1 2 3 4 5]; >> a(2) ans = 2
Arrays in MATLAB
To access elements of D-dimensional arrays, we can use the ()
- perator, passing D arguments.
Ex >> A = ones(3,4,5); >> A(1,3,2) ans = 1 Note: ones(..) creates an array of the specified dimensions and fills it with ones. Similarly, the command zeros(..) creates an array and fills it with zeros.
Manipulating variables
After defining variables, we want to work with them.
- Arithmetic operations
- Logic operations
- String manipulation
- ...
Arithmetic operations
Matlab follows the classic convention on the
- perations precedence:
- Parentheses evaluation
- Exponentiation
- Multiplication and division
- Addition and subtraction
Arithmetic operations
The following expressions all mean different things
- 2^3/2+1
- 2^(3/2)+1
- 2^(3/2+1)
Floating-point arithmetic
Computers use floating point arithmetic. This is basically the binary version of the scientific notation: sign * mantissa * 10^exponent Ex
- 12515 → 1.2515e4
- 1435.003 → 1.435003e3
- 0.000325 → 3.25e-4
Floating-point arithmetic
A floating point number does the same thing, except that the number is expressed in base 2 (it's a binary number). In particular, single precision numbers use 4 bytes (32 bits) as follow:
- 1 bit for the sign
- 8 bits for the exponent
- 23 bits for the mantissa
Floating-point arithmetic
Matlab uses double precision floating-point
- arithmetic. A double uses 64 bits:
- 1 bit for the sign
- 11 bits for the exponent
- 53 bits for the mantissa
Converting a decimal number to a float/double requires conversion to binary. This is beyond the scope of the class.
Floating-point arithmetic
Important observation: having finitely many digits implies that two different numbers become indistinguishable (in f.p. Arithmetic) if their difference goes below a certain threshold. Ex: suppose we use only 3 digits in decimal
- notation. What's the result of the following?
a = 1; a = a + 1e-3;
Floating point arithmetics
In order to perform the addition, let's convert everything to decimal notation for a second. 1 + 1e-3 = 1.000 + 0.001 = 1.001 However, with only 3 digits the “best” approximation we can store of the result is 1. But this means that we didn't modify a!
Floating-point arithmetic
Def: the smallest number ε such that 1+ε≠1 is called machine precision. With doubles, the machine precision is roughly 2e-16. This means that 1 + 1e-16 = 1 in double precision arithmetic.
Logic operations
Matlab also has a type of variable called logical. A logical variable can take two values: true (1) and false (0). >> a = true; >> whos Name Size Bytes Class Attributes a 1x1 1 logical >> a a = 1
Logic operations
Matlab has operators for logical expressions. The syntax is the following
- AND: a && b
- OR: a || b
- NOT: ~a
Note: element-by-element AND/OR are available for arrays with the sintax
- AND: array1 & array2
- OR: array1 | array2
String manipulation
A string value is rarely changed through operations. However, there are some useful functions for strings:
- strcat: concatenates (horizonally) strings
- strfind: find a string within another
- strcmp: compares two strings
- str2num: converts a string to a number (if the string
actually contains a number)
String manipulation
Ex: >> a = 'John'; >> b = 'Smith'; >> strcat(a,b) ans = JohnSmith >> strcmp(a,b) ans = 0 >> strfind('matlab','a') ans = 2 5
Scripts
A script is a file with extension “.m” (short for Matlab), called sometimes m-file, in which you can put your code exactly as you would type it in the prompt. To execute the code you put in the script, simply type the name of the script from command line.
Scripts
Ex: in 'my_file.m' I can put the code a = 'John'; b = 'Smith'; strcmp(a,b) Then, from command line, I can just type >> my_file ans = 0
Scripts
Why using scripts?
- If the code is longer than 3 lines, it will probably take a few
tries to get it right. Putting the code in a script it's easier than typing it many times at the prompt.
- If you code well and give the right name to your scripts, you
might be able to reuse the code in another project.
- If you run a script many times, it's faster to type the name of
the script than to retype the code.
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
- ther 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
- nly 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
- ne, allowing any possible arithmetic
- peration ('+','-','*','/') 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
- therwise
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;
- therwise
'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
- f 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,
- r 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
- f 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. function 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)
- '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
- ne 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
- rder.
- 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
- nes 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.
Checking inputs
Matlab offers one function/variable for this:
- nargin. The name stands for Number of
ARGuments in Input. Ex: quicksort.m
Variable inputs
Matlab goes even further: a function can have an arbitrary number of inputs arguments: function out = my_func(x,y,varargin) Here x and y are variables behaving in the same way as before. Instead, varargin (rigorously lowercase) is a 1-by-N cell array
- f arguments of arbitrary length: N can be anything, from 0 to
infinity (and beyond). To get the actual number of arguments, we can still use nargin. If we want to know the length of varargin, length(varargin).
Variable inputs
Ex: function dummy(name,last_name,varargin) if nargin<2 disp ('Error! Give me at least your name...'); return; end if nargin<3 age = '0'; else age = num2str(varargin{1}); end s = strcat(name,{' '},last_name,' is',{' '},age,{' years
- ld.'});
disp(s);