Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Recap
MATLAB opens into a Command Window where you can
Variable names must start with a letter from the English alphabet, and can consist of numbers and underscore.
Use clear to remove variables from memory. Avoid using inbuilt functions, variables or keywords as your
name is predened.
The help and doc are very useful! There are numerous
elements
How to control the display of output Mathematical, logical and relational operators ifelse, for, while statements MATLAB functions and scripts
Vectors
MATLAB is designed to work with multidimensional arrays of
>> b =
numbers since one of the elements is a real number. In contrast, all the elements of b are displayed as integers.
Vectors
The array elements in the variable b = [1 2 3 4] are in an
arithmetic progression.
Use : to declare such arrays more succintly. >> b = 1 : 4 Basic syntax of : is start : step : end. The default step size is 1. >> b = 1 : 0 . 5 : 3 b = 1.0000 1.5000 3.0000 2.0000 2.5000
Vectors
The dimensions of an array can be obtained by using the size
This says that b is an array (matrix) with 1 row and 5 columns. The size command also takes in a second parameter that indicates the the dimension along which the length is desired. Dimension 1 corresponds to rows and dimension 2 corresponds to columns.
>> size ( b , 2 ) ans = 5 % the number of columns
Vectors
The length command gives the largest dimension of an array >> length ( b ) ans = 5 An empty array is initialized by using the [] construct >> a = [ ] Add elements to an array (it may be empty) as follows: >> a = [ a 1 ] a = 1 >> a = [ 0 a 2 ] a = 0 1 2
Strings
Strings are input naturally as strings, enclosed inside single quotation marks. Strings are simply one dimensional arrays of characters.
>> s = s = this is a string >> size ( s ) ans = 1 16 this is a string
Output display
Use ; (semicolon) to control the display of output. Presence of
Output display
Use the format command to control the display of numbers. See doc format for more options.
format rat to display in rational numbers format short to display in real numbers with 4 digits after
Basic arithmetic operators: +, , , /, Modulo operation: use mod command >> disp ( 2 1 0 + 3 + mod ( 4 , 2 ) ) 1027 >> disp ( 6 / 3 2 ) 4 >> disp (6/3 2+24) 20
Operator precedence
The operations follow a precedence rule for evaluation. See doc precedence. Evaluation is from left to right for operators of
equal precedence.
1. 2. 3. 4. 5. 6. 7. 8. 9. () unary + or , / +, : = =, <, >, <=, >=, = && ||
>> disp ( 6/3 2+24) 12 Use brackets explicitly to make the precedence clear >> disp ((( 6) / 3 ) 2 + ( 2 4 ) ) 12
Control ow
if-else statements are used to conditionally evaluate certain statements.
if <if e x p r e s s i o n > <if s t a t e m e n t s > elseif <elseif e x p r e s s i o n > <elseif s t a t e m e n t s > else <else s t a t e m e n t s > end >> a = 5 ; >> if mod ( a , 2 ) == 0 disp ( 2 d i v i d e s a ) end
Control ow
if-else statements are used to conditionally evaluate certain statements.
>> a = 7 ; >> if mod ( a , 2 ) == 0 disp ( 2 d i v i d e s a ) elseif mod ( a , 3 ) == 0 disp ( 3 d i v i d e s a ) elseif mod ( a , 5 ) == 0 disp ( 5 d i v i d e s a ) else disp ( a i s n o t d i v i s i b l e by 2 , 3 o r 5 ) end a i s n o t d i v i s i b l e by 2 , 3 o r 5
Control ow
for loops are useful to iteratively perform computations.
for < i n d e x > = < a r r a y > <s t a t e m e n t s > end
Control ow
for loops are useful to iteratively perform computations.
for < i n d e x > = < a r r a y > <s t a t e m e n t s > end
Control ow
for loops are useful to iteratively perform computations.
for < i n d e x > = < a r r a y > <s t a t e m e n t s > end
Control ow
while loops are used to conditionally and iteratively compute some expression.
while < e x p r e s s i o n > <s t a t e m e n t s > end
The while loop computes the <statements> in its body as long as the <expression> evaluates to true .
>> s = 0 ; k = 1 ; >> while k <= 10 s = s + k; k = k + 1; end >> disp ( [ s = , num2str ( s ) ] ) s = 55
Control ow
We looked at ifelse, for and while statements. All of them are terminated with the keyword end
Use continue to continue the nearest for or while loop. Below we add all the primes below 10.
>> s = 0 ; >> for k = 1 : 1 0 if i s p r i m e ( k ) c o n t i n u e % skip s=s+k below if k is not prime end s = s + k; % add all primes below 10 end >> disp ( s ) 17
Control ow
We looked at ifelse, for and while statements. All of them are terminated with the keyword end
Use break to exit from nearest for or while loop. Below we determine the next 3 primes after 32.
>> s = 3 2 ; a = [ ] ; >> while length ( a ) < 3 while s <= 100 s = s + 1; if i s p r i m e ( s ) break % exits " while s <=100" end end a = [a s ]; end >> disp ( a ) 37 41 43
MATLAB les
Command window is useful for small programs but not
lengthy programs
Instead create a MATLAB le for long programs: - Filename must contain only letters, numbers or underscore, and must begin with a letter. - Filename must end in .m, e.g. myprogam.m - Call the lename as myprogam from command window - File must be in same directory as the directory shown in Current folder. Alternatively, it can be in your matlabpath (see doc path). Comments can be introduced by using %.
The editor
MATLAB les can be created using any text editor Use Use edit to invoke MATLABs internal editor edit myprogram to open some le called myprogram.m The .m sux is optional If myprogram.m does not exist, MATLAB will create the le in the Current folder
Use edit doc for example to see the contents of the function doc. You can access the source code of other MATLAB
Scripts
Scripts are similar to the commands you write on the command window. The example below is a le called next three primes .m
1 2 3 4 5 6 7 8 9 10
s = 32; a = [ ] ; while length ( a ) < 3 while s <= 100 s = s + 1; if i s p r i m e ( s ) break % exits " while s <=100" end end a = [a s ]; end
Functions
Create and save this function as a le is_divisible_by_2.m in the Current Folder by typing
>> e d i t i s d i v i s i b l e b y 2 .m
1 2 3 4 5 6 7
8 9
10 11
% is_divisible_by_2 (n) % function to test if a number n is divisible by 2 % This function does not return any value , % but prints the result of the test. function i s d i v i s i b l e b y 2 ( n ) if mod ( n , 2 ) == 0 disp ( [ n = , num2str ( n ) , is divisible by 2 ] ) else disp ( [ n = , num2str ( n ) , i s not d i v i s i b l e by 2 ] ) end end
Functions
After saving the le, try out the following commands:
The help command will print out the comments in the
Functions
The second example function that we describe computes the sum of the rst n positive integers, and saved as sum_of_numbers.m.
1 2 3 4 5
6 7 8
9 10 11 12 13
% sum_of_numbers (n) % function to find sum of first n positive integers function o u t p u t = s u m o f n u m b e r s ( n ) output = 0; % first check if the input n is positive . if n is a positive real , % then the array 1:n will behave as 1: floor (n) if n <= 0 error ( t h e i n p u t n must be a p o s i t i v e integer ) end % compute the sum for k = 1 : n , o u t p u t = o u t p u t + k ; end end
Functions
An example usage is the following:
>> s u m o f n u m b e r s ( 1) E r r o r u s i n g s u m o f n u m b e r s ( line 8 ) t h e input n must be a p o s i t i v e i n t e g e r >> s u m o f n u m b e r s ( 1 0 ) ans = 55 >> s = s u m o f n u m b e r s ( 1 0 ) ; >> disp ( [ s = , num2str ( s ) ] ) s = 55
before the function nishes. We do not need to specify a return statement explicitly.
A return statement can be used if you want to exit the
function immediately
more readable
1 2 3 4 5 6
Important notes:
A single le can not contain both functions and scripts. For example, the following le contents will give you an error:
1 2 3 4
function fn1() is accessible from the command window and other les function fn2() is accessible from fn1() since it is inside the same le function fn2() is not accessible from command window or other les
function a s q = f n ( a ) asq = a 2; end Suppose I write the above function to a le called get square .m I can call the function fn by the le name >> g e t s q u a r e ( 2 )
Exercise
1. Test out all the examples given in these slides. Ensure that you understand the main concepts.