0% found this document useful (0 votes)
77 views38 pages

DIPClass Till 26-08-2020

The document discusses M-function programming in MATLAB. It describes that M-files allow MATLAB code to be organized into reusable functions. M-files contain function definitions, help text, and code. Functions take inputs and return outputs, and can be called from the command prompt. Comments are used to document functions. Operators like arithmetic, relational, and logical operators can be used within functions. Flow control statements like if/else, for loops, and while loops allow conditional execution of code.

Uploaded by

vj singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views38 pages

DIPClass Till 26-08-2020

The document discusses M-function programming in MATLAB. It describes that M-files allow MATLAB code to be organized into reusable functions. M-files contain function definitions, help text, and code. Functions take inputs and return outputs, and can be called from the command prompt. Comments are used to document functions. Operators like arithmetic, relational, and logical operators can be used within functions. Flow control statements like if/else, for loops, and while loops allow conditional execution of code.

Uploaded by

vj singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

M-Function Programming

One of the most powerful features of the Image


Processing Toolbox(IPT) is its transparent access to the
MATLAB programming environment.

1
M-Files
 M-files in MATLAB can be scripts that simply execute a
series of MATLAB statements.
 M-files are created using a text editor and are stored with
a name of the form filename. m, such as average. m and
filter . m.
 The components of a function M-file are :
 The function definition line
 The H1 line
 Help text
 The function body
 Comments
2
The function definition line
function [outputs] = name(inputs)
 For example, a function to compute the sum and
product (two different outputs) of two images would
have the form
function [s, p] = sumprod(f, g)
 where f, and g are the input images, s is the sum image,
and p is the product image.
 Functions can be called at the command prompt; for
example,
>> [s, p] = sumprod(f, g);
3
H1 line
 The H1 line is the first text line.
 It is a single comment line that follows the function
definition line.
 There can be no blank lines or leading spaces between
the H1 line and the function definition line.
 Example

% SUMPROD Computes the sum and product of two images

4
Help text
 Help text is a text block that follows the HI line, without
any blank lines in between the two.
 Help text is used to provide comments and online help
for the function.
 When a user types help f unction-name at the prompt,
MATLAB displays all comment lines that appear
between the function definition line and the first
noncomment (executable or blank) line.
 The help system ignores any comment lines that appear
after the Help text block.
>> help function-name 5
Function body
 The function body contains all the MATLAB code that
performs computations and assigns values to output
arguments.

6
Comments
 All lines preceded by the symbol "%" that are not the
HI line or Help text are considered function comment
lines and are not considered part of the Help text
block.
 It is permissible to append comments to the end of a
line of code.
function avg=average(x)
% function average Computes the average of x
avg = sum(x)/numel(x); % the average
End
>> a = average(1:3) % a = (1 + 2 + 3) / 3
a=
2
7
 Scope of function’s variables is confined to within
function. No worry for name conflict with those
outside of function.
 What comes in and goes out are tightly controlled
which helps when debugging becomes necessary.
 Compiled the first time it is used; runs faster
subsequent times.
 Easily be deployed in another project.
 Auto cleaning of temporary variables.
 I/O are highly regulated, if the function requires
many pre-defined variables, it is cumbersome to
pass in and out of the function.

8
Operators
 MATLAB operators are grouped into three main
categories:
 Arithmetic operators that perform numeric computations
 Relational operators that compare operands quantitatively
 Logical operators that perform the functions AND, OR, and
NOT

9
Arithmetic operators
 MATLAB has two different types of arithmetic operations.
 Matrix arithmetic operations are defined by the rules of linear
algebra.
 Array arithmetic operations are carried out element by element and
can be used with multidimensional arrays.
 The period (dot) character (.) distinguishes array operations ' notaion
from matrix operations.
 For example,
 A*B indicates matrix multiplication in the traditional sense,

 A. *B indicates array multiplication, in the sense that the result


is an array, the same size as A and B, in which each element is
the product of corresponding elements of A and B.
10
MATLAB arithmetic operators, where A and B are matrices

11
12
Relational Operators
 Matlab supports the following relational operators:
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
Example for Relational operators
>> A = [1 2 3; 4 5 6; 7 8 9]
>> B = [0 2 4; 3 5 6; 3 4 9]
>> A == B
ans = 0 1 0
0 1 1
0 0 1
 Here in locations where corresponding elements of A and B match 1s
are obtained otherwise 0s are obtained.
>> A >= B
ans = 1 1 0
1 1 1
1 1 1
 Produces a logical array with 1s where the elements of A are greater
than or equal to the corresponding elements of B and 0s elsewhere.
Logical operators and functions
 Matlab supports the following logical operators:
& AND
| OR
~ NOT
 These operators can operate on both logical and
numeric data.
 Matlab treats a logical 1or nonzero numeric
quantity as true and a logical 0 or numeric 0 as
false in all logical tests.
Example for logical operation
>> A = [ 1 2 0; 0 4 5]
>> B = [ 1 -2 3; 0 1 1]
>> A & B
ans = 1 1 0
0 1 1
 And operation produces a 1 at locations where both
operands are nonzero and 0s elsewhere.
Matlab supported logical functions
• xor (exclusive OR) xor function returns a 1 only if both operands are
different; otherwise xor returns a 0.
• all It returns a 1 if all elements in a vector are
nonzero; otherwise it returns a 0. It operates
columnwise on matrices.
• any It returns a 1 if any of the elements in a vector is
nonzero; otherwise any returns a 0. It operates
columnwise on matrices.
>> A = [1 2 3; 4 5 6]
>> B = [0 -1 1; 0 0 2]
>> xor(A,B)
ans = 1 0 0
1 1 0
>> all(A)
ans = 1 1 1
>> any(B)
ans = 0 1 1
Some Important Variables and Constants

A cell array is a data type with


indexed data containers called cells,
where each cell can contain any
type of data. Cell arrays commonly
contain either lists of character
vectors of different lengths, or mixes
of strings and numbers, or
numeric arrays of different sizes.

18
Cell Arrays
• A cell array is a special array of arrays. Each element of the cell array may point to
a scalar, an array, or another cell array.
>> C = cell(2, 3); % create 2x3 empty cell array
>> M = magic(2);
>> a = 1:3; b = [4;5;6]; s = 'This is a string.';
>> C{1,1} = M; C{1,2} = a; C{2,1} = b; C{2,2} = s; C{1,3} = {1};
C=
[2x2 double] [1x3 double] {1x1 cell}
[2x1 double] ‘This is a string.‘ []
>> C{1,1} % prints contents of a specific cell element
ans =
1 3
4 2
>> C(1,:) % prints first row of cell array C; not its content
 Related utilities: iscell, cell2mat

Introduction to MATLAB 19
Some important variables and constants

20
Flow Control
 MATLAB provides the eight flow control statements

21
Conditional statement if has the syntax
 if, else, and elseif Conditional statement if has the
syntax
if expression
statements
end
 The expression is evaluated and yields true, MATLAB
executes one or more commands, denoted here as
statements, between the if and end lines.
 If expression is false, MATLAB skips all the statements
between the if and end lines and resumes execution at
the line following the end line
22
else and elseif statements
if expressionl
statements1
elseif expression2
statements2
else
statements3
end

23
for loop
 a for loop executes a group of statements a speciled number of times.
for index = start:increment:end
statements
end

 nest two or more for loops


for index1 = start1:incrementl:end
statements 1
for index2 = start2:increment2:end
statements2
end
additional loop1 statements
end

24
 Example1
for j=1:5
for i=1:3
a(i, j) = i + j ;
end
end
 Example2
count = 0;
for k = 0:0.1:1
count = count + 1;
end
25
while
 A while loop executes a group of statements for as long as the expression
controlling the loop is t rue.
 The syntax is
while expression
statements
end
 while loops can be nested:
while expression1
statements 1
while expression2
statements2
end
additional loop1 statements
end
26
a = 10;
% while loop execution example
while( a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
end

27
break
 break terminates the execution of a for or while loop.
 When a break statement is encountered, execution continues with the next
' statement outside the loop.
 In nested loops, break exits only from the innermost loop that contains it.
a = 10;
% while loop execution
while (a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
if( a > 15)
% terminate the loop using break statement
break;
end
end
28
 The continue statement passes control to the next iteration of the for or while
loop in which it appears, skipping any remaining statements in the body of the
loop.
 In nested loops, continue passes control to the next iteration of the loop
enclosing it.
a = 9;
%while loop execution
while a < 20
a = a + 1;
if a == 15
% skip the iteration
continue;
end
fprintf('value of a: %d\n', a);
end 29
switch
 A switch block conditionally executes one set of
statements from several choices. Each choice is
covered by a case statement.
switch switch-expression
case case-expression
Statement (s)
case {case-expression1 , case-expression2, . . . }
statement (s)
otherwise
statement (s)
end
30
grade = 'B';
switch(grade)
case 'A'
fprintf('Excellent!\n' );
case 'B'
fprintf('Well done\n' );
case 'C'
fprintf('Well done\n' );
case 'D'
fprintf('You passed\n' );
case 'F'
fprintf('Better try again\n' );
otherwise
fprintf('Invalid grade\n' );
end

31
Vectorizing
 Vectorization - Operations performed over vectors are faster than
those over loops.
 Vectorizing simply means converting for and while loops to
equivalent vector or matrix operations.
 Suppose that we want to generate a 1-D function of the form
f (x) = A sin(x/2π) where x = 0,1,2,. . . , M – 1
 A for loop to implement this computation is
for x = 1 :M % Array indices in MATLAB cannot be 0.
f(x) = A*sin((x - 1)/(2*pi));
end
 Vectorizing it by
X=0:M-1;
F=A*sin((x - 1)/(2*pi));
32
Preallocating Arrays
 To improve code execution time is to preallocate the
size of the arrays used in a program.
 if we are working with two images, f and g, of size 1024
X 1024 pixels, preallocation consists of the statements

>>f=zeros(1024); g=zeros(1024);

33
Interactive I/O
 it is desired to write interactive M-functions that display information See
Appendfx B for and instructions to users and accept inputs from the
keyboard.
 Function disp is used to display information on the screen. Its syntax is
disp(argument)
>A= [1 2; 3 4];
>> disp (A)
1 2
3 4
>> sc = 'Digital Image Processing.';
>> disp(sc)
Digital Image Processing.

34
 Function input is used for inputting data into an M-
function. The basic syntax is
t=input(‘message’);
t=input(‘message’, ’s’); % s – single number

35
36
Strread function
 If the entries are a mixture of characters and numbers,
then we use one of MATLAB'S string processing
functions.
 Of particular interest in the present discussion is
function strread, which has the syntax ,
[a, b, c, . . .] = strread(cstr, 'format', 'param', 'value' )
 This function reads data from the character string cstr,
using a specified format and param/value
combinations.

37
 For example, suppose that we have the string
>> t = '12.6, x2y, z';
 To read the elements of this input into three variables a,
b, and C, we write
>> [a, b, c] = strread(t, '%f%q%q’, 'delimiter', ‘ , ')
a=
12.6000
b=
'x2y'
C=
‘z'
 This function reads one floating point data(%f) and two
character data(%d). The data are separated by , symbol.

You might also like