You are on page 1of 4

MTH 510

30/08/2015

Objective
Introduce Matlab programming;
i) Understand script and M-files and their difference
ii) Learn how to incorporate help comments in a
function
iii) Learn how to create interactive M-files
iv) Learn the role of subfunctions and how they are
accessed
v) Learn how to create and retrieve data files
vi) Learn on vectorization and why it is beneficial
vii) Learn on anonymous function

Programming with MATLAB


Text: Ch 3

Script file

Function files
Function files- start with the word function
function outvar=funcname(arglist)
% help comments
Statements
Outvar=value

Function file: Example

Example: More than one Result

On the Editor window and save as demofunc

On the Editor window and save as demofunc2

On the
Command
window
5

LF_F15

MTH 510

30/08/2015

Difference B/n Script & M-files

Subfunctions
Functions can call subfunctions

The variables are erased


after the M-file is executed

The variables exist after


the script is executed

Interactive M-file: input, display

Command : fprintf

Structured Programming: Decisons


The if structure:

Examples

x == 0

Creating and Accessing Data files


Creating and saving data file (filename.MAT)

Relationship
equal

x ~= 0
x<0
x>0
x <= 0
x >= 0
x > 0& y > 0

Not equal

x > 0| y > 0

If either x OR y is greater than 0

Retrieving data

Less than
Greater than
Less or equal
Greater or equal
If x AND y are greater than zero

11

LF_F15

10

12

MTH 510

30/08/2015

Creating and Accessing Data files

Creating and Accessing Data files


Use the file save as and import to save and retrieve the
work space data

Ascii-formatCreating and saving data file

save filenam.txt -ascii


Retrieving data
load filename

13

Structured Programming: Decisons


The if structure:

Examples

x == 0

14

Example: Decisons

Relationship
equal

x ~= 0
x<0
x>0
x <= 0
x >= 0
x > 0& y > 0

Not equal

x > 0| y > 0

If either x OR y is greater than 0

Less than
Greater than
Less or equal
Greater or equal
If x AND y are greater than zero

15

Decision: with two options

Decision: more than two options

The if ...else structure when you have two options:

The if ...elseif structure when you have more than two


options:

17

LF_F15

16

18

MTH 510

30/08/2015

Loop:for...end

Vectorization of for ... End

Performing repetitive operation for ...end structure:

19

Loop:while structure

20

Annonymous Functions

Loop repeats as long as a logical condition is true

We can create simple function without creating M-file


These functions are defined in the command window

21

22

Function Functions
A function that operates on another function

2.5

1.5

0.5

0
0

0.2

0.4

0.6

0.8

1.2

1.4

1.6

1.8

23

LF_F15

You might also like