MATLAB
MATLAB
MATLAB
After downloading the installer the software can be installed through few
clicks.
Understanding the MATLAB Environment
MATLAB development IDE can be launched from the icon created on the
desktop. The main working window in MATLAB is called the desktop. When
MATLAB is started, the desktop appears in its default layout
Current Folder This panel allows you to access the project folders and files.
Command Window This is the main area where commands can be entered
at the command line. It is indicated by the command prompt (>>).
Workspace The workspace shows all the variables created and/or imported
from files.
Command History This panel shows or rerun commands that are entered at
the command line.
Hands on Practice
Type a valid expression, for example,
5+5
ans = 10
When you click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is
ans = 9
Another example,
When you click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is
ans = 1
Another example,
When you click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is
ans = Inf
warning: division by zero
Another example,
732 * 20.3
When you click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is
ans = 1.4860e+04
For example,
x = 3;
y=x+5
When you click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is
y= 8
Adding Comments
The percent symbol (%) is used for indicating a comment line. For example,
You can also write a block of comments using the block comment operators
% { and % }.
The MATLAB editor includes tools and context menu items to help you add,
remove, or change the format of comments.
Operator Purpose
+ Plus; addition operator.
\ Left-division operator.
/ Right-division operator.
. Decimal point.
= Assignment operator.
Name Meaning
Inf Infinity.
pi The number
Naming Variables
Variable names consist of a letter followed by any number of letters, digits
or underscore.
MATLAB is case-sensitive.
Variable names can be of any length, however, MATLAB uses only first N
characters, where N is given by the function namelengthmax.
For example,
save myfile
You can reload the file anytime later using the load command.
load myfile
MATLAB will execute the above statement and return the following result
x=3
It creates a 1-by-1 matrix named x and stores the value 3 in its element.
Let us check another example,
MATLAB will execute the above statement and return the following result
x=4
Once a variable is entered into the system, you can refer to it later.
When an expression returns a result that is not assigned to any variable, the
system assigns it to a variable named ans, which can be used later.
For example,
sqrt(78)
MATLAB will execute the above statement and return the following result
ans = 8.8318
sqrt(78);
9876/ans
MATLAB will execute the above statement and return the following result
ans = 1118.2
x = 7 * 8;
y = x * 7.89
MATLAB will execute the above statement and return the following result
y = 441.84
Multiple Assignments
You can have multiple assignments on the same line. For example,
a = 2; b = 7; c = a * b
MATLAB will execute the above statement and return the following result
c = 14
who
MATLAB will execute the above statement and return the following result
whos
MATLAB will execute the above statement and return the following result
The clear command deletes all (or the specified) variable(s) from the
memory.
Long Assignments
Long assignments can be extended to another line by using an ellipses (...).
For example,
initial_velocity = 0;
acceleration = 9.8;
time = 20;
final_velocity = initial_velocity + acceleration * time
MATLAB will execute the above statement and return the following result
final_velocity = 196
For example
format long
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result
x = 17.2319816406394
Another example,
format short
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result
x = 17.232
The format bank command rounds numbers to two decimal places. For
example,
format bank
daily_wage = 177.45;
weekly_wage = daily_wage * 6
MATLAB will execute the above statement and return the following result
weekly_wage = 1064.70
For example,
format short e
4.678 * 4.9
MATLAB will execute the above statement and return the following result
ans = 2.2922e+01
format long e
x = pi
MATLAB will execute the above statement and return the following result
x = 3.141592653589793e+00
The format rat command gives the closest rational expression resulting
from a calculation. For example,
format rat
4.678 * 4.9
MATLAB will execute the above statement and return the following result
ans = 34177/1491
Creating Vectors
A vector is a one-dimensional array of numbers. MATLAB allows creating
two types of vectors:
Row vectors
Column vectors
For example,
r = [7 8 9 10 11]
MATLAB will execute the above statement and return the following result
r=
7 8 9 10 11
Another example,
r = [7 8 9 10 11];
t = [2, 3, 4, 5, 6];
res = r + t
MATLAB will execute the above statement and return the following result
res =
9 11 13 15 17
MATLAB will execute the above statement and return the following result
c=
7
8
9
10
11
Creating Matrices
A matrix is a two-dimensional array of numbers.
m = [1 2 3; 4 5 6; 7 8 9]
MATLAB will execute the above statement and return the following result
m=
1 2 3
4 5 6
7 8 9
Command Purpose
Command Purpose
Command Purpose
The fscanf and fprintf commands behave like C scanf and printf functions.
They support the following format codes
%s Format as a string.
%d Format as an integer.
The format function has the following forms used for numeric display
Format Display up to
Function
Command Purpose
Plotting Commands
MATLAB provides numerous commands for plotting graphs. The following
table shows some of the commonly used commands for plotting
Command Purpose
In previous chapters, you have learned how to enter commands from the
MATLAB command prompt. MATLAB also allows you to write series of
commands into a file and execute the file as complete unit, like writing a
function and calling it.
The M Files
MATLAB allows writing two kinds of program files
Scripts script files are program files with .m extension. In these files, you
write series of commands, which you want to execute together. Scripts do not
accept inputs and do not return any outputs. They operate on data in the
workspace.
Functions functions files are also program files with .m extension. Functions
can accept inputs and return outputs. Internal variables are local to the
function.
You can use the MATLAB editor or any other text editor to create
your .mfiles. In this section, we will discuss the script files. A script file
contains multiple sequential lines of MATLAB commands and function calls.
You can run a script by typing its name at the command line.
If you are using the command prompt, type edit in the command prompt.
This will open the editor. You can directly type edit and then the filename
(with .m extension)
edit
Or
edit <filename>
The above command will create the file in default MATLAB directory. If you
want to store all program files in a specific folder, then you will have to
provide the entire path.
Let us create a folder named progs. Type the following commands at the
command prompt (>>):
Alternatively, if you are using the IDE, choose NEW -> Script. This also
opens the editor and creates a file named Untitled. You can name and save
the file after typing the code.
NoOfStudents = 6000;
TeachingStaf = 150;
NonTeachingStaf = 20;
Total = NoOfStudents + TeachingStaf ...
+ NonTeachingStaf;
disp(Total);
After creating and saving the file, you can run it in two ways
Just typing the filename (without extension) in the command prompt: >> prog1
6170
Example
a = 5; b = 7;
c=a+b
d = c + sin(b)
e=5*d
f = exp(-d)
When the above code is compiled and executed, it produces the following
result
c= 12
d= 12.657
e= 63.285
f= 3.1852e-06
If the variable already exists, then MATLAB replaces the original content
with new content and allocates new storage space, where necessary.
For example,
Total = 42
The above statement creates a 1-by-1 matrix named 'Total' and stores the
value 42 in it.
Example
When the above code is compiled and executed, it produces the following
result
Following table provides the functions for determining the data type of a
variable
Function Purpose
is Detect state
Example
x=3
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = 23.54
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = [1 2 3]
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
x = 'Hello'
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x=3
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x = 1177/50
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x=
1 2 3
ans = 0
ans = 1
ans = 1
ans = 0
x = Hello
ans = 0
ans = 0
ans = 1
ans = 0
ans = 0
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operations
Set Operations
Arithmetic Operators
MATLAB allows two different types of arithmetic operations
The matrix operators and array operators are differentiated by the period
(.) symbol. However, as the addition and subtraction operation is same for
matrices and arrays, the operator is same for both cases. The following
table gives brief description of the operators
Show Examples
Operator Description
Relational Operators
Relational operators can also work on both scalar and non-scalar data.
Relational operators for arrays perform element-by-element comparisons
between two arrays and return a logical array of the same size, with
elements set to logical 1 (true) where the relation is true and elements set
to logical 0 (false) where it is not.
Show Examples
Operator Description
== Equal to
~= Not equal to
Logical Operators
MATLAB offers two types of logical operators and functions:
Show Examples
Bitwise Operations
Bitwise operators work on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
MATLAB provides various functions for bit-wise operations like 'bitwise and',
'bitwise or' and 'bitwise not' operations, shift operation, etc.
The following table shows the commonly used bitwise operations:
Show Examples
Function Purpose
Set Operations
MATLAB provides various functions for set operations, like union,
intersection and testing for set membership, etc.
Show Examples
Function Description
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operations
Set Operations
Arithmetic Operators
MATLAB allows two different types of arithmetic operations
The matrix operators and array operators are differentiated by the period
(.) symbol. However, as the addition and subtraction operation is same for
matrices and arrays, the operator is same for both cases. The following
table gives brief description of the operators
Show Examples
Operator Description
*
Matrix multiplication. C = A*B is the linear algebraic
product of the matrices A and B. More precisely,
Relational Operators
Relational operators can also work on both scalar and non-scalar data.
Relational operators for arrays perform element-by-element comparisons
between two arrays and return a logical array of the same size, with
elements set to logical 1 (true) where the relation is true and elements set
to logical 0 (false) where it is not.
Show Examples
Operator Description
== Equal to
~= Not equal to
Logical Operators
MATLAB offers two types of logical operators and functions:
Show Examples
Bitwise Operations
Bitwise operators work on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
MATLAB provides various functions for bit-wise operations like 'bitwise and',
'bitwise or' and 'bitwise not' operations, shift operation, etc.
Show Examples
Function Purpose
Set Operations
MATLAB provides various functions for set operations, like union,
intersection and testing for set membership, etc.
Show Examples
Function Description
setdiff(A,B,'rows')
Treats each row of A and each row of B as
single entities and returns the rows from A
that are not in B. The rows of the returned
matrix are in sorted order.
Decision making structures require that the programmer should specify one
or more conditions to be evaluated or tested by the program, along with a
statement or statements to be executed if the condition is determined to be
true, and optionally, other statements to be executed if the condition is
determined to be false.
Statement Description
An if ... end statement consists
if ... end statement
of a boolean expression followed
by one or more statements.
There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially. The first
statement in a function is executed first, followed by the second, and so on.
MATLAB supports the following control statements. Click the following links
to check their detail.
Control Statement Description
Row vectors
Column vectors
Row Vectors
Row vectors are created by enclosing the set of elements in square
brackets, using space or comma to delimit the elements.
r = [7 8 9 10 11]
MATLAB will execute the above statement and return the following result
r=
7 8 9 10 11
Column Vectors
Column vectors are created by enclosing the set of elements in square
brackets, using semicolon to delimit the elements.
MATLAB will execute the above statement and return the following result
c=
7
8
9
10
11
MATLAB will execute the above statement and return the following result
ans = 3
When you reference a vector with a colon, such as v(:), all the components
of the vector are listed.
MATLAB will execute the above statement and return the following result
ans =
1
2
3
4
5
6
rv = [1 2 3 4 5 6 7 8 9];
sub_rv = rv(3:7)
MATLAB will execute the above statement and return the following result
sub_rv =
3 4 5 6 7
Vector Operations
In this section, let us discuss the following vector operations
Transpose of a Vector
Appending Vectors
Magnitude of a Vector
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]
MATLAB will execute the above statement and return the following result
a=
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
Referencing the Elements of a Matrix
To reference an element in the mth row and nth column, of a matrix mx, we
write
mx(m, n);
For example, to refer to the element in the 2 nd row and 5thcolumn, of the
matrix a, as created in the last section, we type
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(2,5)
MATLAB will execute the above statement and return the following result
ans = 6
Let us create a column vector v, from the elements of the 4 th row of the
matrix a:
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
v = a(:,4)
MATLAB will execute the above statement and return the following result
v=
4
5
6
7
You can also select the elements in the m th through nth columns, for this we
write
a(:,m:n)
Let us create a smaller matrix taking the elements from the second and
third columns
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(:, 2:3)
MATLAB will execute the above statement and return the following result
ans =
2 3
3 4
4 5
5 6
In the same way, you can create a sub-matrix taking a sub-part of a matrix.
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(:, 2:3)
MATLAB will execute the above statement and return the following result
ans =
2 3
3 4
4 5
5 6
In the same way, you can create a sub-matrix taking a sub-part of a matrix.
3 4 5
4 5 6
To do this, write
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
sa = a(2:3,2:4)
MATLAB will execute the above statement and return the following result
sa =
3 4 5
4 5 6
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a( 4 , : ) = []
MATLAB will execute the above statement and return the following result
a=
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(: , 5)=[]
MATLAB will execute the above statement and return the following result
a=
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
Example
In this example, let us create a 3-by-3 matrix m, then we will copy the
second and third rows of this matrix twice to create a 4-by-3 matrix.
new_mat =
4 5 6
7 8 9
4 5 6
7 8 9
Matrix Operations
In this section, let us discuss the following basic and commonly used matrix
operations
Division of Matrices
Transpose of a Matrix
Concatenating Matrices
Matrix Multiplication
Determinant of a Matrix
Inverse of a Matrix
For example
zeros(5)
MATLAB will execute the above statement and return the following result
ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
For example
ones(4,3)
MATLAB will execute the above statement and return the following result
ans =
1 1 1
1 1 1
1 1 1
1 1 1
For example
eye(4)
MATLAB will execute the above statement and return the following result
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
For example
rand(3, 5)
MATLAB will execute the above statement and return the following result
ans =
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
0.1270 0.0975 0.9575 0.9706 0.8003
A Magic Square
A magic square is a square that produces the same sum, when its
elements are added row-wise, column-wise or diagonally.
magic(4)
MATLAB will execute the above statement and return the following result
ans =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Multidimensional Arrays
An array having more than two dimensions is called a multidimensional
array in MATLAB. Multidimensional arrays in MATLAB are an extension of the
normal two-dimensional matrix.
a = [7 9 5; 6 1 9; 4 3 2]
MATLAB will execute the above statement and return the following result
a=
7 9 5
6 1 9
4 3 2
a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9]
MATLAB will execute the above statement and return the following result
a=
ans(:,:,1) =
0 0 0
0 0 0
0 0 0
ans(:,:,2) =
1 2 3
4 5 6
7 8 9
We can also create multidimensional arrays using the ones(), zeros() or the
rand() functions.
For example,
b = rand(4,3,2)
MATLAB will execute the above statement and return the following result
b(:,:,1) =
0.0344 0.7952 0.6463
0.4387 0.1869 0.7094
0.3816 0.4898 0.7547
0.7655 0.4456 0.2760
b(:,:,2) =
0.6797 0.4984 0.2238
0.6551 0.9597 0.7513
0.1626 0.3404 0.2551
0.1190 0.5853 0.5060
Where,
a = [9 8 7; 6 5 4; 3 2 1];
b = [1 2 3; 4 5 6; 7 8 9];
c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0])
c(:,:,1) =
9 8 7
6 5 4
3 2 1
c(:,:,2) =
1 2 3
4 5 6
7 8 9
c(:,:,3) =
2 3 1
4 7 8
3 9 0
Array Functions
MATLAB provides the following functions to sort, rotate, permute, reshape,
or shift array contents.
Function Purpose
transpose Transpose
Examples
ans = 8
ans = 4
ans = 23
a=
1 2 3
4 5 6
7 8 9
b=
7 8 9
1 2 3
4 5 6
c=
8 9 7
2 3 1
5 6 4
Sorting Arrays
Create a script file and type the following code into it
v=
23 45 12 9 5 0 19 17
ans =
0 5 9 12 17 19 23 45
m=
2 6 4
5 3 9
2 0 1
ans =
2 0 1
2 3 4
5 6 9
ans =
2 4 6
3 5 9
0 1 2
Cell Array
Cell arrays are arrays of indexed cells where each cell can store an array of
a different dimensions and data types.
The cell function is used for creating a cell array. Syntax for the cell
function is
C = cell(dim)
C = cell(dim1,...,dimN)
D = cell(obj)
Where,
dim is a scalar integer or vector of integers that specifies the dimensions of cell
array C;
dim1, ... , dimN are scalar integers that specify the dimensions of C;
obj is One of the following:
Example
c = cell(2, 5);
c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5}
c=
{
[1,1] = Red
[2,1] = 1
[1,2] = Blue
[2,2] = 2
[1,3] = Green
[2,3] = 3
[1,4] = Yellow
[2,4] = 4
[1,5] = White
[2,5] = 5
}
Enclosing the indices in braces {}, to refer to the data within individual cells
When you enclose the indices in first bracket, it refers to the set of cells.
For example:
c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};
c(1:2,1:2)
MATLAB will execute the above statement and return the following result
ans =
{
[1,1] = Red
[2,1] = 1
[1,2] = Blue
[2,2] = 2
}
You can also access the contents of cells by indexing with curly braces.
For example
MATLAB will execute the above statement and return the following result
ans = Blue
ans = Green
ans = Yellow
If you want to create a row vector, containing integers from 1 to 10, you
write
1:10
MATLAB executes the statement and returns a row vector containing the
integers from 1 to 10
ans =
1 2 3 4 5 6 7 8 9 10
If you want to specify an increment value other than one, for example
100: -5: 50
ans =
100 95 90 85 80 75 70 65 60 55 50
0:pi/8:pi
ans =
Columns 1 through 7
0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562
Columns 8 through 9
2.7489 3.1416
You can use the colon operator to create a vector of indices to select rows,
columns or elements of arrays.
The following table describes its use for this purpose (let us have a matrix
A)
Format Purpose
Example
Create a script file and type the following code in it
A = [1 2 3 4; 4 5 6 7; 7 8 9 10]
A(:,2) % second column of A
A(:,2:3) % second and third column of A
A(2:3,2:3) % second and third rows and second and third columns
A=
1 2 3 4
4 5 6 7
7 8 9 10
ans =
2
5
8
ans =
2 3
5 6
8 9
ans =
5 6
8 9
MATLAB supports various numeric classes that include signed and unsigned
integers and single-precision and double-precision floating-point numbers.
By default, MATLAB stores all numeric values as double-precision floating
point numbers.
You can choose to store any number or array of numbers as integers or as
single-precision numbers.
Function Purpose
x=
x=
x=
38 23 45
x=
38 23 45
x=
38 23 45
x=
38 23 45
Example
Let us extend the previous example a little more. Create a script file and
type the following code
x=
38 23 45
x=
38 23 45
x=
{
[1,1] = 38
[1,2] = 23
[1,3] = 45
}
Both the functions take the integer data type as the argument, for example,
intmax(int8) or intmin(int64) and return the maximum and minimum values
that you can represent with the integer data type.
Example
The following example illustrates how to obtain the smallest and largest
values of integers. Create a script file and write the following code in it
Both the functions when called with the argument 'single', return the
maximum and minimum values that you can represent with the single-
precision data type and when called with the argument 'double', return the
maximum and minimum values that you can represent with the double-
precision data type.
Example
The following example illustrates how to obtain the smallest and largest
floating point numbers. Create a script file and write the following code in it
MATLAB will execute the above statement and return the following result
whos
MATLAB will execute the above statement and return the following result
Example
Create a script file and type the following code into it
str_ascii =
84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116
84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116
Using the MATLAB concatenation operator [] and separating each row with a
semicolon (;). Please note that in this method each row must contain the same
number of characters. For strings with different lengths, you should pad with
space characters as needed.
Using the char function. If the strings are of different lengths, char pads the
shorter strings with trailing blanks so that each row has the same number of
characters.
Example
doc_profile =
Zara Ali
Sr. Surgeon
R N Tagore Cardiology Research Center
doc_profile =
Zara Ali
Sr. Surgeon
RN Tagore Cardiology Research Center
You can combine strings horizontally in either of the following ways
Using the MATLAB concatenation operator, [] and separating the input strings
with a comma or a space. This method preserves any trailing spaces in the
input arrays.
Using the string concatenation function, strcat. This method removes trailing
spaces in the inputs.
Example
MATLAB cell array can hold different sizes and types of data in an array. Cell
arrays provide a more flexible way to store strings of varying length.
The cellstr function converts a character array into a cell array of strings.
Example
{
[1,1] = Zara Ali
[2,1] = Sr. Surgeon
[3,1] = R N Tagore Cardiology Research Center
}
Function Purpose
Examples
FORMATTING STRINGS
A = pi*1000*ones(1,5);
sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)
ans = 3141.592654
3141.59
+3141.59
3141.59
000003141.59
JOINING STRINGS
str1 = red-blue-green-yellow-orange
str2 = red,blue,green,yellow,orange
new_student =
{
[1,1] = Poulomi Dutta
}
first_names =
{
[1,1] = Zara
[1,2] = Neha
[1,3] = Monica
[1,4] = Madhu
[1,5] = Madhu
[1,6] = Bhawna
[1,7] = Nuha
[1,8] = Reva
[1,9] = Sunaina
[1,10] = Sofia
}
COMPARING STRINGS
Functions can accept more than one input arguments and may return more
than one output arguments.
Example
The following function named mymax should be written in a file
named mymax.m. It takes five numbers as argument and returns the
maximum of the numbers.
Create a function file, named mymax.m and type the following code in it
The first line of a function starts with the keyword function. It gives the
name of the function and order of arguments. In our example,
the mymax function has five input arguments and one output argument.
The comment lines that come right after the function statement provide the
help text. These lines are printed when you type
help mymax
MATLAB will execute the above statement and return the following result
MATLAB will execute the above statement and return the following result
ans = 89
Anonymous Functions
An anonymous function is like an inline function in traditional programming
languages, defined within a single MATLAB statement. It consists of a single
MATLAB expression and any number of input and output arguments.
You can define an anonymous function right at the MATLAB command line
or within a function or script.
This way you can create simple functions without having to create a file for
them.
f = @(arglist)expression
Example
result1 = 343
result2 = 7
result3 = 1.0000e-10
result4 = 9.5459
Primary functions can be called from outside of the file that defines them,
either from command line or from other functions, but sub-functions cannot
be called from command line or other functions, outside the function file.
Sub-functions are visible only to the primary function and other sub-
functions within the function file that defines them.
Example
Let us write a function named quadratic that would calculate the roots of a
quadratic equation. The function would take three inputs, the quadratic co-
efficient, the linear co-efficient and the constant term. It would return the
roots.
The function file quadratic.m will contain the primary function quadratic and
the sub-function disc, which calculates the discriminant.
quadratic(2,4,-4)
MATLAB will execute the above statement and return the following result
ans = 0.7321
Nested Functions
You can define functions within the body of another function. These are
called nested functions. A nested function contains any or all of the
components of any other function.
Nested functions are defined within the scope of another function and they
share access to the containing function's workspace.
Example
Let us rewrite the function quadratic, from previous example, however, this
time the disc function will be a nested function.
quadratic2(2,4,-4)
MATLAB will execute the above statement and return the following result
ans = 0.73205
Private Functions
A private function is a primary function that is visible only to a limited group
of other functions. If you do not want to expose the implementation of a
function(s), you can create them as private functions.
Private functions reside in subfolders with the special name private.
Example
Let us rewrite the quadratic function. This time, however, the disc function
calculating the discriminant, will be a private function.
quadratic3(2,4,-4)
MATLAB will execute the above statement and return the following result
ans = 0.73205
Global Variables
Global variables can be shared by more than one function. For this, you
need to declare the variable as global in all the functions.
If you want to access that variable from the base workspace, then declare
the variable at the command line.
The global declaration must occur before the variable is actually used in a
function. It is a good practice to use capital letters for the names of global
variables to distinguish them from other variables.
Example
Let us create a function file named average.m and type the following code
in it
global TOTAL;
TOTAL = 10;
n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
av = average(n)
When you run the file, it will display the following result
av = 35.500