Professional Documents
Culture Documents
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.
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.
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
6
Another Examples of Scripts
Scripts: Evaluate
7
Conditional flow control - if, else, and elseif
Syntax
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.
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
<solution>
The equation can be express with matrix
exponential form as,
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, {}.
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
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.
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
Examples
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 ba .
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)