Sei sulla pagina 1di 35

MH2401 Algorithms & Computing III Slides 2

Chua Chek Beng Henk Hollmann Punarbasu Purkayastha

August 19, 2013

Recap
MATLAB opens into a Command Window where you can

interactively enter commands


Use the diary command to record your input and output. Variables can be declared by assigning values to them.

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

function names or variable names.


If unsure, look up the documentation or use the functions iskeyword or which to determine if your function or variable

name is predened.
The help and doc are very useful! There are numerous

examples in them. Explore them!

Topics for today


How to create vectors Using : operator create vectors with regularly spaced

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

data. All objects in MATLAB are arrays of elements.


A vector is a one-dimensional array. To declare a vector, separate the elements by spaces.

Optionally, use comma.


>> a = 1.5000 2.0000 b = [1 2 3 4] 3.0000 4.0000 a = [1.5 2 3 4]

>> b =

MATLAB considered all the elements of a as oating point

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

command. For instance,


>> size ( b ) ans = 1 5

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

a semicolon suppresses the output and separates statements.


Use disp to print the value of any variable or expression. >> a = 1 : 3 ; b = 2 ; disp ( b ) 2 >> disp ( 2 3 ) 8 Use num2str and disp to display multiple items on the same

line, by creating an array of strings. num2str converts arrays of numbers to strings.


>> disp ( [ a = , num2str ( a ) , num2str ( b ) ] ) a = 1 2 3, b = 2 , b = ,

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

decimal point. This is the default.


format long to display 15 digits after the decimal point. >> a = [ 1 / 3 i 2 / 3 ] ; disp ( a ) % the default format 0 0.3333 i 0.6667 >> format rat >> disp ( a ) 0 1/3 i 2/3 >> format l o n g >> disp ( a ) 0 0.333333333333333 i 0.666666666666667

Mathematical and Relational operators

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

Mathematical and Relational operators


Logical operators: && (and), || (or) , (not) Relational operators: = =, <, >, <=, >=, = >> disp (6/3 2 == 1 | | 2/3/2 > 1 ) 0 >> disp ( isstr ( 1 ) ) 1 >> disp ( cos ( 0 ) == argument isn t 1 >> disp ( cos ( 0 ) == argument isn t 0 1 | | 0 == 1 ) % second evaluated 0 && 0 == 0 ) % second evaluated

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

>> s = 0 ; >> for k = 1 : 1 0 s = s + k; end >> disp ( [ s = , num2str ( s ) ] ) s = 55

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

The <array> in the for loop can be any array!


>> s = 0 ; >> for k = [ 1 4 9 16 2 5 ] s = s + k; end >> disp ( [ s = , num2str ( s ) ] ) s = 55

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

The <array> in the for loop can be any array!


>> s = 0 ; >> for k = sin ( 1 : 0 . 1 : 1 0 ) s = s + k; end >> disp ( [ s = , num2str ( s ) ] ) s = 13.931 sin(<array>) computes the sine of each element of the <array>

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 %.

Use comments generously in your les!

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

commands in this way.

Functions and scripts


MATLAB les can be of two types: Scripts: These are les containing commands as one would run them on the command line. The script is run by invoking the name of the le in which it is saved. Once the script is run, all its variables are available in the command window workspace. Functions: These are les whose rst non-commented line starts with the keyword function.
% <comments > function [ out1 , o u t 2 ] = f u n c n a m e ( arg1 , a r g 2 ) <s t a t e m e n t s > end

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

The variables a, s will be in command workspace after it is run.


>> n e x t t h r e e p r i m e s ; disp ( a ) 37 41 43

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

beginning of the le.


>> help i s d i v i s i b l e b y 2 i s d i v i s i b l e b y 2 (n) function t o t e s t if a number n i s d i v i s i b l e by 2 T h i s function d o e s n o t return any v a l u e , but p r i n t s the r e s u l t o f the t e s t . The function itself can be called like any other function >> i s d i v i s i b l e b y 2 ( 1 0 ) n = 10 i s d i v i s i b l e by 2 >> i s d i v i s i b l e b y 2 ( 1 ) n = 1 i s n o t d i v i s i b l e by 2

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

Functions return and print


Things to note:
In function is divisible by 2 (n), we did not return anything.

We only printed some output.


In function sum of numbers(n) we are returning the value of output. This means that the calling command can store this

output in a variable and use it later


>> s = s u m o f n u m b e r s ( 1 0 ) ; % s stores the return value The return value of output is the last value that output has

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

Functions and scripts


Line continuation
Very long lines can be split into multiple lines by using ellipses ... Programs with short lines (75 80 characters) are generally

more readable
1 2 3 4 5 6

% The following vector is a very long vector v = [ 1 1 2 3 5 8 13 21 34 . . . 55 89 9 0 ] ; p = 1; for k = v p = pk ;

Functions and scripts

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

a =5; function a s q = f n ( a ) asq = a 2; end

Functions and scripts Important notes:


Only the topmost function in a le is accessible from outside
1 2 3 4 5 6 7

function o u t = f n 1 ( n ) out = fn2 ( n ) ; end function o u t 2 = f n 2 ( n ) out2 = n 2; end

 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

Functions and scripts Important notes:


The le name determines the name by which you can call a function.
1 2 3

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 )

 The following will not work


>> f n ( 2 ) % error ! MATLAB doesn t know about fn If le name is get square .m, name the topmost function in your le get square

Exercise

1. Test out all the examples given in these slides. Ensure that you understand the main concepts.

Potrebbero piacerti anche