You are on page 1of 23

Chapter 04:

M-file Programming

By J.S. Park
Incheon National University
M-Files
A programming language enables you to write a series of MATLAB statements into a file.
Then, execute them with a single command.
You write your program in an ordinary text file, giving the file a name of filename.m.

Types of Program Files

Scripts Functions
Difference Simply execute a series of MATLAB Accept input arguments and return
statements. output arguments.
No input arguments
No return output arguments.
File name No internal (function) name. If file name and function name are
different,
MATLAB ignores the internal (function)
name.
Data They operate on data in the workspace. Internal variables are local to the function.
Store variables in the workspace. Local variables can be accessed by input
Share variables with other scripts and and output arguments.
with the MATLAB command line Global variables can be shared with other
interface functions and/or in the workspace.

2
Function Definition Line

Function Name. Begin with a letter, can contain any alphanumeric characters or underscores.

Function Arguments.
Multiple output values - enclose the output argument list in square brackets.
Input arguments - enclosed in parentheses, if present.
Use commas to separate multiple input or output arguments.

Example:
function [x, y, z] = sphere(theta, phi, rho)
If there is no output, leave the output blank
function printresults(x) or use empty square brackets:
function [] = printresults(x)

Comments
Comment lines begin with a percent sign (%).

Example,
% Add up all the vector elements.
y = sum(x) % Use the sum function.

3
Creating a Program File
1 Create an M-file using 2 Call the M-file from the
a text editor: command line, or from
within another M-file.

function c=myfile(a,b) >>a=2;


c=(a.^2)+(b.^2) >>b=3;
>>c=myfile(a,b)
c=
13

 Open a new file(Using Text Editors):


- New > File from the File menu at the top of the MATLAB Command Window.
- From the MATLAB command line
edit foo opens the editor on the file foo.m.
Omitting a file name opens the editor on an untitled file.

 List the names of the files in your current folder:


>>what
function f = fact(n) Function definition line
% Compute a factorial value. H1 line Any line that begins with % is not
% FACT(N) returns the factorial of N, Help text executable
% usually denoted by N! H1 line is displayed when you
% Put simply, FACT(N) is PROD(1:N). Comment request help.
f = prod(1:n); Function body 4
Path
Path displays the current MATLAB search path.
The search path is stored in the file pathdef.m.

Select File > Set Path, or type


pathtool
in the Command Window and
press Enter.

5
Examples of Function M-file and Script M-file
Command window Edit window
Function M-file Script M-file
File name is fact.m File name is scrpt_fact.m

1. Script an M-file: >>a=3;


>>b=5; % script M-file
>>add_test01
c= c=a+b
8

2. Function M-file: >>c=add_test_02(3,5) function [z]= add_test02(x, y)


c=
8 % Addition of a and b
% add_test02(x,y) returns the
% result of x+y

 After execution of script m file z = x+y;


“add_test01.m", type
whos
then, you can see the variable a, b and c
are created in the base workspace

6
Another Examples of Scripts

Scripts: Evaluate

% Script file firstgraph. >>testgraph


x = pi/100:pi/100:10*pi;
y = sin(x)./x;
plot(x,y)
grid

7
Conditional flow control - if, else, and elseif
Syntax

if expression1 function y = testif( x )


commands (evaluated if expression 1 is true) if x <0
elseif expression 2
commands (evaluated if expression 2 is true) y=x;
elseif … disp('input value is negative')
...
elseif x>=10 && x<=20
else
commands (executed if all previous expressions y=x+5;
evaluate to false) disp('input value is between 10 and 20')
end
elseif x<5 || x>100
< Less than y=x+10;
<= Less than or equal to disp('input value is less than 5 or …
> Greater than
greater than 100')
>= Greater than or equal to
else
== Equal to
y=x^2;
~= Not equal to
end
& Logical AND
| Logical OR
~ NOT
&& AND
|| OR
8
Recursion
a function can call itself during its own execution.

function y = ten_exp(n)
% This is a recursive program for computing y = 10^n.
% The program works only if n is a nonnegative integer.
% If n is negative, the algorithm won't stop.
if n == 0
y=1
else
n %<< this line is not needed but for inspection
y = 10 * ten_exp(n-1)
end

9
Conditional flow control - switch and case
Switch among several cases based on expression.
function [x, z] = testswitch( x )
Syntax
switch x
switch expression (scalar or string) case {1,2,3}
z=x^2;
case value1 (executes if expression evaluates to
disp('The input value is 1, 2, or 3')
value1) case 4
z = sqrt(x);
commands
disp('The input value is 4 ')
case value2 (executes if expression evaluates to otherwise
z = x;
value2)
disp('Return the input value')
commands end
...
if x==1 || x==2 || x==3
otherwise z=x^2;
disp('The input value is 1, 2, or 3')
statements
elseif x== 4
end z = sqrt(x);
disp('The input value is 4 ')
else
z = x;
disp('Return the input value')
end

10
Repeating with for loops
The commands between the for and end statements are executed for all values stored in the
array.

Syntax The for loops can be nested

for k = array H = zeros(5);


for m=1:5
commands
for n=1:5
end H(m,n) = 1/(m+n-1);
end
for n=0:10 end
x(n+1) = sin(pi*n/10);
end
>>H
>>x H=
x= 1.0000 0.5000 0.3333 0.2500 0.2000
Columns 1 through 7 0.5000 0.3333 0.2500 0.2000 0.1667
0 0.3090 0.5878 0.8090 0.9511 1.0000 0.9511 0.3333 0.2500 0.2000 0.1667 0.1429
Columns 8 through 11 0.2500 0.2000 0.1667 0.1429 0.1250
0.8090 0.5878 0.3090 0.0000 0.2000 0.1667 0.1429 0.1250 0.1111

A = zeros(3);
A loop free version might look like this
for m=1:3
for n=1:3 k = 1:10;
A(m,n) = sin(m)*cos(n); A = sin(k)'*cos(k);
end
end

11
Example with for loops
Linear, Constant coefficient, Ordinary differential X=[];
equations can be expressed as, X0=[1 1 1]';
A=[0 -6 -1;6 2 -16;-5 20 -10];
dx
 Ax
dt for t=0:.01:1
X=[X expm(t*A)*X0];
 0 6 1  end
Let A   6 2 16  and
  plot3(X(1,:),X(2,:),X(3,:),'-o')
 5 20 10 
grid on

the initial value is 1


x(0)  1
1

Find the solution x(t ) in 0  t  1 .

<solution>
The equation can be express with matrix
exponential form as,

x(t )  etA x(0)


Now, we can write down the MATLAB expressions
that will correctly compute the above equation as
follows:

12
Repeating with while loops
This loop is used when the programmer does not know the number of repetitions a priori.

Syntax Example :
q = pi; >>q
while expression q=
while q > 0.01
statements q = q/2; 0.0061
end end

break q = pi;
while q
The break statement lets you exit early from a for loop or q = q/2;
while loop. if q <= 0.01
In nested loops, break exits from the innermost loop only. q
break
end
end
continue

The continue statement passes control to the next iteration of the for loop or
while loop.
Execution continues at the beginning of the loop in which the continue
statement was encountered.

13
Multidimensional Arrays

Multidimensional Arrays

Multidimensional arrays in the MATLAB environment are arrays with more than
two subscripts..

For example,
>>R = randn(3,4,5);
creates a 3-by-4-by-5 array with a total of 3*4*5 = 60 normally distributed
random elements.

A=ones(3,4);
for k=1:24
M(:,:,k)=A*k;
end

>>size(M)
ans =
3 4 24

14
Cell Arrays
Cell Arrays

Cell arrays in MATLAB are multidimensional arrays whose elements are copies of other
arrays.
A cell array of empty matrices can be created with the cell function.
Cell arrays are created by enclosing a miscellaneous collection of things in curly braces, {}.

You can use three-dimensional arrays to store a sequence of matrices of the


same size. Cell arrays can be used to store a sequence of matrices of different
sizes.

M=cell(8,2)
for n=1:8
M{n,1}=magic(n);
M{n,2}=ones(n)*n;
end

M=
[ 1] [ 1]
[2x2 double] [2x2 double]
[3x3 double] [3x3 double]
[4x4 double] [4x4 double]
[5x5 double] [5x5 double] M{n,1}
[6x6 double] [6x6 double]
[7x7 double] [7x7 double]
[8x8 double] [8x8 double] M{n,2}
15
Characters and Text
Enter text into MATLAB using single quotes. >>S = char('A','rolling','stone','gathers','momentum.')
% produces a 5-by-9 character array:
1-by-5 character array. S=
A
>>s = 'Hello‘
rolling
stone
Converts to ASCII codes for each character. gathers
>>a = double(s) momentum
a=
72 101 108 108 111 >>C = {'A';'rolling';'stone';'gathers';'momentum.'}
% creates a 5-by-1 cell array
C=
Reverses the conversion.
'A'
>>s = char(a) 'rolling'
'stone'
Joins the strings horizontally and produces 'gathers'
>>h = [s, ' world'] 'momentum.'
h=
You can convert a character array to a cell array of strings
Hello world
with
>>C = cellstr(S)
Joins the strings vertically and produces
>>v = [s; 'world'] and reverse the process with
v= >>S = char(C)
Hello
world

16
Structures
Structures are multidimensional MATLAB arrays: Creates a numeric row vector containing the score
Following creates a scalar structure with three fields: field of each element of structure array S:
>>scores = [S.score]
>>S.name = 'Ed Plum'; scores =
>>S.score = 83; 83 91 70
>>S.grade = 'B+‘
S= >>avg_score = sum(scores)/length(scores)
name: 'Ed Plum' avg_score =
score: 83 81.3333
grade: 'B+'
To create a character array from one of the text fields:
The fields can be added one at a time, >>names = char(S.name)
S(2).name = 'Toni Miller'; names =
S(2).score = 91; Ed Plum
S(2).grade = 'A-'; Toni Miller
Jerry Garcia
or an entire element can be added:
S(3) = struct('name','Jerry Garcia‘,'score',70,'grade','C'); You can create a cell array within curly braces:
>>names = {S.name}
>>S names =
S= 'Ed Plum' 'Toni Miller' 'Jerry Garcia'
1x3 struct array with fields:
name To separate variables outside of the structure,
score enclosing them all within square brackets:
grade >>[N1 N2 N3] = S.name
If you type N1 =
S.score Ed Plum
N2 =
it is the same as typing Toni Miller
S(1).score, S(2).score, S(3).score N3 =
Jerry Garcia 17
Anonymous Functions and Inline Functions
• A single MATLAB expression and any number of input and output arguments.
• You can define the functions right at the MATLAB command line, or within a function or script.
• A function that will be used during the current MATLAB session only

Anonymous Functions Inline Functions

The syntax : >>f = inline('sqrt(x.^2+y.^2)','x','y')


f = @(arglist)expression f=
Example : Inline function:
sqr = @(x) x.^2; f(x,y) = sqrt(x.^2+y.^2)

To execute,
Evaluate
>> a = sqr(5)
a= >>f(3,4)
25 ans =
5
>>A = [1 2;3 4] ;
>>B = ones(2);
>>C = f(A, B)
C=
1.4142 2.2361
3.1623 4.1231
18
Function Nesting
You can define functions within
the body of another function.

In this example, function B is


nested in function A:

function x = A(p1, p2)


...
B(p2)
function y = B(p3)
...
end
...
end

19
Global Variables
To share variables in more than one function,
declare the variables as global in all the functions.

Do the same thing at the command line if you want the base workspace to
access the variable.

The global declaration must occur before the variable is actually used in a
function.

Using capital letters for the names of global variables helps distinguish them
from other variables.

Example :
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;

Evaluation :
>>global GRAVITY
>>GRAVITY = 32;
>>y = falling((0:.1:5)');
20
The eval Function
Execute a string containing a MATLAB expression

eval(expression) executes expression, a string containing any valid MATLAB expression. You can
construct expression by concatenating substrings and variables inside square brackets:
expression = [string1,int2str(var),string2,...]

Syntax

eval(expression) eval(expression,catch_expr) [a1,a2,a3,...] = eval(function(b1,b2,b3,...))

eval('[a1,a2,a3,...] = function(var)') % not recommended


[a1,a2,a3,...] = eval('function(var)') % recommended syntax

Examples

This for loop generates a sequence of 5 matrices named M1 through M5:

for n = 1:5
magic_str = ['M',int2str(n),' = magic(n)'];
eval(magic_str)
end

21
The feval Function
b
h h2

a
f ( x)dx  [ f (a)  f (b)]  [ f (a)  f (b)]
2 12 where h ba .

Implement this formula in MATLAB

function y = corrtrap(fname, fpname, a, b)


% Corrected trapezoidal rule y.
% fname - the m-file used to evaluate the integrand,
% fpname - the m-file used to evaluate the first derivative of the integrand,
% a,b - endpoinds of the interval of integration.
h = b - a;
y = (h/2).*(feval(fname,a) + feval(fname,b))+ (h.^2)/12.*(feval(fpname,a) - feval(fpname,b));

Evaluate

>> a = [0 0.1];
>>b = [pi/2 pi/2 + 0.1];
>>y = corrtrap('sin', 'cos', a, b)
y=
0.9910 1.0850
22
Rounding to integers. Functions ceil, floor, fix and round

Evaluate
>> randn('seed', 0)
% This sets the seed of the random numbers generator to zero
>>T = randn(5)

T= >>A = floor(T) >>C = fix(T)


1.1650 1.6961 -1.4462 -0.3600 -0.0449 A= C=
1 1 -2 -1 -1 1 1 -1 0 0
0.6268 0.0591 -0.7012 -0.1356 -0.7989
0 0 -1 -1 -1 0 0 0 0 0
0.0751 1.7971 1.2460 -1.3493 -0.7652 0 1 1 -2 -1 0 1 1 -1 0
0.3516 0.2641 -0.6390 -1.2704 0.8617 0 0 -1 -2 0 0 0 0 -1 0
-1 0 0 0 -1 0 0 0 0 0
-0.6965 0.8717 0.5774 0.9846 -0.0562
>>B = ceil(T) >>D = round(T)
B= D=
2 2 -1 0 0 1 2 -1 0 0
1 1 0 0 0 1 0 -1 0 -1
1 2 2 -1 0 0 2 1 -1 -1
1 1 0 -1 1 0 0 -1 -1 1
0 1 1 1 0 -1 1 1 1 0
23

You might also like