You are on page 1of 138

Matlab Level 1 Summer 2008

Alexandria Student Branch 1



Session 1
Content
- What is Matlab ?
- Introducing the Matlab Development Environment
- Performing Basic Arithmetic, Logical and Relational Operations
- Defining Arrays
- Array and Matrix Operations
- Matrix Functions
- Scalar-Matrix operations
- Matlab Help System
- Using help & lookfor
- Clearing current directory & workspace
- Adding comments in Matlab
- Tasks


What is Matlab?
The name Matlab stands for matrix laboratory. It is a high-performance language
for technical computing. It integrates computation, visualization, and programming in
an easy-to-use environment where problems and solutions are expressed in familiar
mathematical notation. Typical uses include:
Math and computation
Algorithm development
Modeling, simulation, and prototyping
Data analysis, exploration, and visualization
Scientific and engineering graphics
Application development, including graphical user interface building
Matlab is an interactive system whose basic data element is an array that does not
require dimensioning. This allows you to solve many technical computing problems,
especially those with matrix and vector formulations, in a fraction of the time it would
take to write a program in a scalar non-interactive language such as C or Fortran.



Matlab Level 1 Summer 2008



Alexandria Student Branch 2

Introducing the Matlab Development Environment

If you happen to get employed in a new place, the first thing you would probably
do is to take a brief tour to experience your new workplace and its subdivisions, or
what we alternatively refer to by the term Development Environment. For someone
working in a factory, the development environment refers to the work place with all its
subdivisions and all the resources and tools it contains. For Matlab users, the
development environment refers similarly to the Matlab window and all the resources
and tools it contains. The first step in understanding how Matlab works is to experience
its development environment. When you start Matlab, the figure on the next page
depicts what you will see.


The Command Window
The command window is an interpreter where you can write and execute
instructions one at a time or few at a time. You know where to write your next
instruction from the >> mark, which is called the command prompt.

The Workspace Browser
The workspace is the group of variables (arrays) you are working with. The
workspace browser provides you with an overview of the workspace, meaning that it
Matlab Level 1 Summer 2008



Alexandria Student Branch 3

shows you the variable you have created so far. It shows you the variable name, size,
data type and its value if the value is compact enough to be displayed, such as that of
a single number or few characters. By double clicking on any variable, you get to
inspect this variable in detail.

The Command History
It is an archive of commands previously executed in the command window. You
may use it to retrieve and re-execute previous commands. The command window
doesnt log your commands from the day you first opened Matlab; it has a maximum
buffer size. Once reached, any new command will append to the bottom of the buffer,
causing the topmost command to be lost. By setting the buffer size to 10,000 for
instance, you can make the command window remember your last 10,000
commands.

The Current Directory
Below the workspace, you can see a tab selection that lets you select either the
workspace or the current directory to view. Click on the Current Directory tab. The
current directory is a folder you choose to be your default working folder. Whenever
Matlab requires a user file, it will start its search by looking into this folder. Whenever
Matlab needs to save a user file, it will save it in this folder by default.

The rest of the elements of the development environment do not appear at start-
up by default, but you can call them whenever you need them. We continue our
discussion of the development environment by looking at the rest of its elements.

The Array Editor
The array editor is a window that opens to show you the contents of a variable
(array) and possibly make you change these contents. The array editor opens when
you double click on a variable in the workspace browser. The figure below shows an
instant of the array editor opened to show us variable ImA, a matrix resulting from
loading an image into the workspace.

Matlab Level 1 Summer 2008



Alexandria Student Branch 4


The M-File Editor
The M-File Editor is a text-entry window where you can write down complete
programs. The following figure depicts the M-File editor.

Matlab Level 1 Summer 2008



Alexandria Student Branch 5



You can start the M-File editor by typing edit at the command prompt (>>edit)
or by clicking the New M-File button on the startup screen.



The M-File editor contains facilities for writing, debugging and running your
programs.
Matlab Level 1 Summer 2008



Alexandria Student Branch 6

The Figure Window
A figure window is a window used with graphics. A graphic cannot be displayed in
the command window. Therefore it opens in a separate window equipped with facilities
for handling graphic, which is the figure window.



The GUI Development Environment (GUIDE)
The GUIDE is a tool for building GUIs like the one shown above. The GUIDE may
be started by typing guide at the command prompt (>>guide) or by going to New ->
GUI in the Matlab File menu.

Matlab Level 1 Summer 2008



Alexandria Student Branch 7



The development environment for GUIs will then open. The GUI tool looks as
depicted in the figure below.



Matlab Level 1 Summer 2008



Alexandria Student Branch 8

Simulink
Simulink is a Matlab-associated package used for system design, modeling and
system analysis. The figure below shows an example of a house thermodynamic
subsystem designed using Simulink.




The Matlab development environment contains many other elements used for
performing specialized tasks. We will mostly be dealing with those elements we have
mentioned above.







Matlab Level 1 Summer 2008



Alexandria Student Branch 9

Basic Arithmetic, Relational and Logical Operations

Now we want to start using Matlab to perform some very simple operations,
including arithmetic, relational and logical operations.

It is important to understand how Matlab handles operations. Let us consider the
following expression. An expression is an operation and an assignment as explained
below.
E = 2 + 3

Matlab always starts by evaluating the right-hand-side (RHS) of the expression, which
is (2 + 3). This operation evaluates to (5). So Matlab will try to assign the value 5 to
the left-hand-side (LHS), which is (E). However, the variable (E) does not exist yet, so
Matlab will create a variable called (E) then carry out the assignment. Hence the result
of this expression is that E equals 5.

Note:
- If the variable E already existed, its previous contents will be replaced by the
result of evaluating the new expression.
- If the expression contains an operation without a LHS variable to which the result
may be assigned, Matlab automatically uses a default variable called ans
standing for answer. To try this, write (>> 2+3).
- If you append any expression by a semicolon (;), the expression will be
evaluated normally, but the output of its evaluation wont be reported in the
command prompt.

Arithmetic Operations

The following table shows a list of the available arithmetic operations and their
description.

Operation Operator Syntax Example
Addition + c=a+b F=F+2
Subtraction - c=a-b B=2-7
Multiplication * c=a*b C=2*pi
Division / c=a/b Rad=deg*pi/180
Exponentiation ^ (Shift 6) c=a^b H=2^B

Matlab Level 1 Summer 2008



Alexandria Student Branch 10


Logical Operations

In arithmetic operations, the operands may have any numerical values. In logical
operations, the operands may have one of two values: either nonzero or zero (also
called true or false).
In input operands, 0 is used to indicate (logic 0), while any number other than 0
may be used to indicate (logic 1). In the results of a logical operation, a 0 is always
used to indicate (logic 0) while a 1 is always used to indicate (logic 1).

Operation Operator Syntax Example
Logical AND & (ampersand) (shift 7) c = a & b F=1 & 0
Logical OR | (shift \) c = a | b A = A | B
Logical Inversion ~ (tilda) c = ~a C=~6
Logical XOR xor c = xor(a,b) D=xor(D,C)

Note:
- Other logical operations such as NANDing, NORing and XNORing may be
performed by combining two or more of the previous operators. Example:
c=~(A|B) is equivalent to NORing A with B then assigning the result to c.
- Logic 0 is also referred to as False, and logic 1 is also referred to as True.

Examples:
>>a=5;b=2;c=0;
>>x=a&b; %x=1
>>y=c&b; %y=0
>>z=c|b; %z=1
>>w=~b; %w=0

Note:
You can get up to the previous commands by using the up and down arrows.


Relational Tests

Relational operations are simple in their concept. A relational operation is a test
done on a certain expression. Hence, they are also called relational tests. The test
evaluates to (Logic 1) if the expression is true and evaluates to (Logic 0) if the
expression is false.

Matlab Level 1 Summer 2008



Alexandria Student Branch 11




Operation Description
A > B The result is true if A is greater than B, and is false otherwise
A < B The result is true if A is smaller than B, and is false otherwise
A>=B True if A is greater than or equal to B, false otherwise
A<=B True if A is smaller than or equal to B, false otherwise
A==B The result is true is A is equal to B, and is false otherwise
A~=B The result is true is A is not equal to B, and is false otherwise

Examples:
>>a=5;b=2;
>>x=a>b; %x=1
>>x=(a~=b) %x=1

Note:
Many users confuse the double equality sign (==) used in relational tests with
the equality sign (=) used in assignments. When a user uses (=) instead of
(==), Matlab usually reports that an expected relational operator wasnt found.

Combining Different Operations

Different operations may be combined. For instance, let us assume that we want
to operate an alarm mechanism if an automatic temperature alarm button is pressed
and the room temperature exceeds the nominal by 5 degrees.
The status of the automatic temperature alarm button is 0 if the button is not
pressed and is 1 if the button is pressed. The temperature is read by a sensor. We may
use Matlab interfacing techniques to read the status of the button and the value of the
temperature into 2 variables STATUSon and Temp respectively. We want to create a
variable Alarm which is 1 if the button is pressed and the temperature exceeds the
nominal temperature Nominal by 5. The expression used to compute such variable is:

Alarm = STATUSon & (Temp>(Nominal+5))

Using Matlab interfacing techniques, we may send A through a port to the alarm
activation circuit.

Note:
Matlab Level 1 Summer 2008



Alexandria Student Branch 12

- We may combine arithmetic, logical and relational operations.
- Whenever 2 or more operations are combined, the rules of precedence have to
be carefully considered. It is then recommended to use brackets whenever you
are not totally sure no precedence confusions might occur.
Matlab Level 1 Summer 2008



Alexandria Student Branch 13

Defining Arrays

The Nature of Variables in Matlab

Variables in Matlab may be single numbers (scalars), 1-D arrays (vectors), or N-
D arrays (Matrices). The following table shows this notation together with one possible
application of each nature of variables.

Nature Dimensions Examples
Scalar 1-by-1 Number of elements in a vector
Vector 1-by-N or N-by-1 Sound Waves, Voltage Signals,etc.
Matrix M-by-N-by-P Images, Videos, Data Structuresetc.

Note:
Variables in Matlab are case sensitive.

Defining Scalars

>> a=1;

Defining Matrices

=
1 2 1
3 4 3
1 2 2
A
>> A = [2 2 1; 3 4 3; 1 2 1];

Elements on a single row may be separated by white spaces or by commas.
Semicolons must be used to separate elements of different rows.

Defining Vectors
| |

=
=
1
4
2
7 3 1
C
B

>> B = [1 3 7];
>> C = [2;4;1];



Matlab Level 1 Summer 2008



Alexandria Student Branch 14


Some Array Generating Functions

Typing in large arrays may be boring, error prone and time consuming. For this
purpose, we may utilize functions which generate special arrays. We describe here two
of the most important array generating functions.

Syntax Description Example
A=zeros(n,m) Generate an N-by-M array of zeros A=2+zeros(7,8)
B=ones(n,m) Generate an N-by-M array of ones B=4*ones(6,2)
C=eye(n,m) Generate an N-by-M array of ones in their
main diagonal
C=eye(5,3)

Matlab Level 1 Summer 2008



Alexandria Student Branch 15

Array & Matrix Operations

Matrices are arrays. However, matrix operations are not the same as array
operations. Matrix operations use laws of matrix algebra. Array operations are
element-by-element operations carried out on arrays of numbers.

Arithmatic operations:
Matrix addition and array addition are identical. Matrix subtraction and array
subtraction are identical. This is because the laws of matrix algebra define matrix
addition and subtraction to be carried out in an element-by-element fashion.
Matrix multiplication and array multiplication are two different operations.
For example, let A and B be two arrays (matrices) defined as follows.

=
2 2 2
2 2 2
2 2 2

1 0 0
0 1 0
0 0 1
B A
Addition & subtraction of A and B is done in an element-by-element fashion.

= +
3 2 2
2 3 2
2 2 3
B A




=
1 2 2
2 1 2
2 2 1
B A
Matrix multiplication of A and B is done in the row-times-column fashion
defined in matrix algebra. The result of matrix multiplication of A and B is:

=
2 2 2
2 2 2
2 2 2
* B A
Array multiplication of A and B is done in an element-by-element fashion. This
means that the element in row 1 column 1 (R1C1) of the output array is the product of
the element in R1C1 in A and the element in R1C1 in B. The same applies for the rest
of the elements. We use the notation .* as an operator for array multiplication.

=
2 0 0
0 2 0
0 0 2
*B A
Matrix division does not exist. However, array division exists, and we use ./ as its
operator. Array division is an element-by-element division.

=
16 16 32 32
16 16 32 32
32 32 64 64
32 32 64 64
/
4 4 2 2
4 4 2 2
2 2 1 1
2 2 1 1

64 64 64 64
64 64 64 64
64 64 64 64
64 64 64 64
B A B A
Matlab Level 1 Summer 2008



Alexandria Student Branch 16

Array exponentiation is different than matrix exponentiation. The array
exponentiation operation A.^3 is equivalent to the product of array-multiplying A and
A, array-multiplied by A. The matrix exponentiation operation A^3 is equivalent to the
product of matrix-multiplying A and A, matrix-multiplied by A. The result of array
exponentiation is equivalent to exponentiating every element in the array alone.
i.e: A^3 A*A*A & A.^3 A.*A.*A

The table below summarizes the different matrix and array operations.

Operation Syntax Description
M. Addition A+B Element-by-element addition
A. Addition A+B Element-by-element addition
M. Subtraction A-B Element-by-element subtraction
A. Subtraction A-B Element-by-element subtraction
M. Multiplication A*B Row-times-column multiplication
A. Multiplication A.*B Element-by-element multiplication
Inverse M. Mult. A\B Inverse of A M. multiplied by B
M. Inverse Mult. A/B A M. multiplied by the inverse of B
A. Division A./B Element-by-element division
M. Exponentiation A^n Equivalent to A*A*A*A
A. Exponentiation A.^n Element-by-element exponentiation
Transposition A Transpose of the array (matrix) A

When we carry out matrix or array multiplications, some rules have to be regarded to
make the operation doable. Violating these rules might result in Matlab reporting an
error.

Operation Rule
M. Addition The sizes of A and B must be the same
A. Addition The sizes of A and B must be the same
M. Subtraction The sizes of A and B must be the same
A. Subtraction The sizes of A and B must be the same
M. Multiplication Number of Columns of A must equal the number of rows of B
Matlab Level 1 Summer 2008



Alexandria Student Branch 17

A. Multiplication The sizes of A and B must be the same
Inverse M. Mult. The matrix must be square
M. Inverse Mult. The matrix must be square
A. Division The sizes of A and B must be the same
M. Exponentiation The matrix must be square
A. Exponentiation No rule
Transposition No rule


Note:
Logical & Relational operations are carried element by element.
Matlab Level 1 Summer 2008



Alexandria Student Branch 18

Some Matrix Functions

A function in Matlab is a module (program) that accepts some input(s), carries
out certain computation and produces one or more outputs. We will take a look at
some matrix-related functions.

Function Syntax Description Example
Determinant B=det(A) B (a number)is the determinant
of A (a square matrix)
C=2*det(A)
Inverse D=inv(A) D (a square matrix) is the
inverse of A (a square matrix)
A=inv(B*C)
Rank N=rank(A) N (a number) is the rank of A (a
matrix)
h= rank(A)-1
Diagonal A=diag(C) A is the main diagonal elements
of C
A=2+diag(B)
Sum A=sum(B) A is the sum of all elements of
B if it is a vector or sum of
columns of B if it is a matrix
A=sum(x)
Transpose A=transpose(b) A is the none conjugate
transpose of b
A=transpose(b)
Or
A=b.

Note:
- Transpose(x) x.
- x. is a non conjugate transpose of x where it only replaces the raws by the
columns.
- x is a conjugate transpose of x where it replaces the rows by the columns and
get the conjugate of imaginary numbers.
- When dealing with only real numbers, x is the same as x.

Example:
Define any 2 square matrix A and B. Check that A/B A*inv(B) and A\B
inv(A)*B.



Matlab Level 1 Summer 2008



Alexandria Student Branch 19

Scalar-Matrix operations

We have seen that any array operation requires both of its operands to have the same
size. However, there is one exception. If one of the operands is a scalar and the other
is any array in general, Matlab uses this scalar in operating on every element of the
array. For example, (>>A=A+2) adds 2 to all elements of A. (>>C=2*B+4) multiplies
by 2 then adds 4 to every element of B and then stores the result in C.

The same concept applies to logical, relational and hybrid operations. The instruction
(>>C=~((B+5)>A)) where B is an array and A is a scalar will add 5 to all elements of
B and compare the result with scalar A. Logic 1 will result for all elements that satisfy
B+5>A and logic 0 will result otherwise. But after negation, the logic levels will be
complemented. The resulting logic levels will be stored in variable C.
i.e.: The scalar is extended to the same size of the matrix to carry up the wanted
operation. It has no restricted rule.

Examples:
>>a=2+zeros(5,10);
>>b=3*ones(2,3);
>>x=2+a;
>>y=b/3;
>>b&3;











Matlab Level 1 Summer 2008



Alexandria Student Branch 20

Using Matlab Help System

Matlab comes with a comprehensive help system (documentation) covering all of
its functionality. A clever Matlab user is not a user that memorizes a huge load of
methods and tricks. A clever Matlab user is a user who has good ability to:
- Reach the help section describing anything he/she needs, and
- Deal powerfully with the help material in order to understand what he/she needs.

For this reason, it is as important to learn how to use the Matlab Help system
effectively as it is to understand basic Matlab methods such as entering matrices.
To consult the Matlab documentation, go to the Help menu and select Full
Product Family Help as shown.



The help window will then open. It looks as shown on the next page. Note that it
consists of a Help Navigator Bar shown on the left, and a display pane on the rest of
the screen. The help navigator may be used in many different modes.

Matlab Level 1 Summer 2008



Alexandria Student Branch 21




Contents
Here, the help topics are sorted by topics and sub-topics so that you can reach
for any topic by tracing it down the hierarchy. It requires you to know approximately
where your topic might be found.

Index
Here, you search using keywords related to the function or method you are
looking for.

Search
Similar to Index, but it is a bit slower because it extends its search into the help
texts themselves, not just hovering over the main descriptions as with Index.

Demos
Here, you can access the available Matlab demos, but dont expect to find demos
related exactly to what you need help about.

For example, if you need to find out what function calculates the sine of a
number, the following shows how you may proceed.

Matlab Level 1 Summer 2008



Alexandria Student Branch 22



Using help & lookfor

When we need a function that serves a certain purpose but we dont know that
function at all, we can reach this function and understand everything about it in 2
steps:
1. Discovering the function name given a word or few words that describe its
purpose,
2. Understanding how this function is used given the function name.

The first step may be carried out using the Index and Search features of the help
navigator. The second step may be carried out using the help function.

The function help is a function that you may use to display the help
documentation of a certain function in the command prompt. It may be used if you
know the name of a function but you still want to know or you cant remember how
this function is used. The syntax is (>>help sin). This displays the help of the sine
function.

If you know exactly the function syntax, you can use lookfor instead of help. As an
example if you dont know that the sine function is sin and you tried (>>help sine),
Matlab Level 1 Summer 2008



Alexandria Student Branch 23

then you will find no function with the name sine.But if you tried (>>lookfor sine),
Matlab will begin searching in its function for a function that contain the word sine in
its syntax or description.
You can stop Matlab search using (Ctrl+C)buttons or (Ctrl+PauseBreak)buttons.

Clearing Command Window & Workspace

You can use the command clc to clear command window. Also you can use the
command clear to clear the workspace from all the defined variables.

Adding comments in Matlab

You can type whatever comments you want by putting the % symbol and writing the
comment after it.
Example:
>>a=b+c; %This command adds b,c and puts the result in a.
Matlab Level 1 Summer 2008



Alexandria Student Branch 24

Session 1 Tasks:

1) It is required to use Matlab to solve the following set of equations.
66 9 3 4
127 6 5 17 13
135 11 9 8 7 6
19 2 2 5
152 21 6 5 3 2
5 4 2 1
5 4 3 2
5 4 3 2 1
4 3 1
5 4 3 2 1
= + + +
= + + +
= + + + +
= + +
= + + + +
x x x x
x x x x
x x x x x
x x x
x x x x x

a) Use the zeros function to create an empty 5-by-5 matrix (A) for
the coefficients and an empty 5-by-1 column vector (B) for the
RHSs of the equations.
b) Use the array editor to populate the coefficients into matrix (A).
c) Use the command prompt to populate the RHSs into vector (B).
d) Explain how we can use the rank function to find out whether or
not the 5 equations are independent enough to assign unique
solutions for the 5 unknowns.
e) Write down an expression for a variable S that is true if the rank of
(A) is equal to the number of variables in the case above and false
otherwise.
f) Solve the set of linear equations for x
1
through x
5
.

2) Use the Matlab help system to find the names of the following:
a) The exponential function (e
x
),
b) A function that returns the natural logarithm (ln) of a number,
c) Functions that return the base-2 and base-10 logarithms of a number,
d) A function that gets the square root of a number.

3) Use the Matlab help & try to understand the use of the following two functions:
Sound & Image.












Matlab Level 1 Summer 2008



Alexandria Student Branch 25

Session 2

Content
- Using the Colon Notation (F:S:L)
- Using linspace
- Concatenation
- Indexing into Arrays
- Advanced Array Operations using indexing
- Tasks


Using Colon Notation (F:S:L)

If we wish to generate a vector of uniformly distributed numbers, such as [3 4 5
6]. If the vector is that small, there would be no problem in entering it manually. How
about a case where we want to generate a vector of uniformly distributed numbers
ranging from pi to pi with a step of pi/100? This would be very tedious to do
manually. In this case we can use the F:S:L notation to generate the desired vector.
In F:S:L, F stands for the first number, L stands for the last number and S
stands for the step. We may generate the vector t=[3 4 5 6] by typing

>>t=3:1:6

instead of entering it manually. To generate a vector of numbers uniformly distributed
from pi to pi with a step of pi/100, we may write

>>d=-pi:pi/100:pi;

Note that we have used the semicolon here to suppress the output as the
resulting vector will be 201 elements longs.

As another example, we may want to generate an arithmetic sequence whose
initial term is 3 and whose common difference is 4.5 and whose last term is 39. This
may be done using the following command.

>>as=3:4.5:39;

Matlab Level 1 Summer 2008



Alexandria Student Branch 26

Counting down is as easy as counting up. We may construct a vector of
decreasing values by making the first number greater than the last number and using
a negative step. Take the following for example.

>>seq=9:-3:-18;

The result would be seq=[9 6 3 0 -3 -6 -9 -12 -15 -18].

Note:
If the step is equal to positive 1, it may be omitted from the notation. This is only true
for a step of positive 1. This is not true in case of negative 1.

Example:
The following two commands are equivalent.

>>x=5:1:9;
>>x=5:9;
Note:
No error will get up if you typed the first element bigger than the last element in case
of increasing step or if you typed the first element smaller than the last element in
case of decreasing step. Only an empty matrix is generated.

Example:

>>x=9:2:1; % The result is x=[]
>>y=4:-1:7; % The result is y=[]
>>a=5:2; %Remember the default step is +1

Note:
The matrix will stop at the last element or before it if it cant reach the last number.

Example:
>>x=4:2:9; %The result is x=[4 6 8]

Note:
The resulted matrix is a raw vector. To have a column vector, you can use matrix
transpose.




Matlab Level 1 Summer 2008



Alexandria Student Branch 27

Using linspace

The function linspace is another function which may be used to generate
sequences of uniformly distributed numbers. The main difference between using colon
notation and using linspace is that colon notation asks for the first number, last
number and step while linspace asks for the first number, last number and the
number of points. The syntax of linspace is as follows.

>>t=linspace(first, last, number of points);

If we use the colon notation to produce a vector of numbers ranging from 0 to 10
with a step of 0.1, the resulting vector would be as follows.

t=[0.0 0.1 0.2 0.3 0.4 ..9.6 9.7 9.8 9.9 10.0]

The number of elements of this vector is 101 elements. If you wished to restrict the
number of elements to 100, then the step wont be exactly 0.1; it would be 0.101.

If you wanted to generate the 100 numbers instead of the 101 illustrated above,
you would either have to recompute the step (to get the 0.101 instead of the 0.1), or
you may use linspace as follows: >>t=linspace(0,10,100); .


Using Size Function

The function size is a function use to determine the size of a matrix. The size of the
matrix means number of rows and columns of that matrix. The size matrix can be
written in two styles depending on the number of output arguments. This can be
shown in the following example.
%Define matrix a to be a 56 matrix

%First style, the output is a 2 element matrix where the first element is the number of
%rows while the second is the number of columns
>>t=size(a); %Then t=[5 6]

%Second style, there are two outputs. The first for the row number while the second
%for the column number
>>[r,c]=size(a) %Then r=5,c=6

You can use the size function to generate a matrix with the same size of another
matrix.
Matlab Level 1 Summer 2008



Alexandria Student Branch 28

Example:
>>x=ones(size(a));

Concatenation

Concatenation is the process of joining two things end-to-end. The following
figure illustrates the concatenation of two pipes.




In Matlab, it is often very important to concatenate 2 or more matrices or vectors
into a new extended matrix or vector. When we concatenate 2 pipes, the diameters of
both pipes must be the same. Similarly, when concatenating two matrices, some rule
of size will arise.
Let us start by an example. Assume that we have 2 matrices A and B as defined
below. It is required to create a matrix C which is the concatenation of A and B.

=
8 7 4 3
6 5 2 1

8 7
6 5

4 3
2 1
C B A

This concatenation is called horizontal concatenation. It may be done by the following
command.

>>C=[A B]

The concatenation rule here is that the number of rows of A and B must be equal. If
so, the concatenation will be successful, and the number of rows of C will be the same
as that of A or B, and the number of columns of C will equal the sum of the numbers of
columns of A and B.

Vertical concatenation is as shown below. Note that a similar rule of
concatenation exists for this case. The number of columns of A and B must be the
same.
Matlab Level 1 Summer 2008



Alexandria Student Branch 29

=
8 7
6 5
4 3
2 1

8 7
6 5

4 3
2 1
C B A
The vertical concatenation shown above may be accomplished using the command
(>>C=[A;B];)

It is also possible to carry out horizontal and vertical concatenation at the same
time. The concatenation rule in this case will be that the horizontal concatenation and
vertical concatenation both have their rules satisfied. Look at the following example.

=
16 15 12 11
14 13 10 9
8 7 4 3
6 5 2 1
16 15
14 13

12 11
10 9
8 7
6 5

4 3
2 1
E
D C
B A

This concatenation may be accomplished using the command (>>E=[A B;C D];).

Look at the following examples, and try to figure out what the result of
concatenation is. A is a 2-by-2 square matrix and t is a 1-by-10 vector.
- >>C=[A [5 8;9 4]];
- >>C=[A A A];
- >>C=[A A; A A];
- >>C=[A [5 8; 9 2]; [4 2; 3 5] 2*A];
- >>t2=[t;t];
- >>t2=[t 10:-1:1];
- >>t2=[t; 1:10];

Applications of concatenation include definition of piecewise continuous functions,
tiling of images side to side (3-D concatenation), joining sound segments after one
another, and much more.

Note:
In many applications of concatenation, you need firsly to define an empty matrix. This
can be done simply as follows: >>x=[];.
Matlab Level 1 Summer 2008



Alexandria Student Branch 30

Indexing into Arrays

Indexing into 2-D Arrays

Let us define an array (A) as shown below and then try to reach for and deal
with certain elements of this array.

=
4 3
2 1
A
In the Matlab syntax, we can access the element in row i column j of a matrix A by
writing A(i,j). This means that for the matrix A shown above:
- A(1,1)=1
- A(1,2)=2
- A(1,3)=3
- A(1,4)=4

So far, we have indexed one element in an array. The next step is to index part
of the array, i.e. a sub-array of the array. To do so, we must use a vector of i's and/or
a vector of js as needed. Let us start by a simple example. Consider the following
matrix (Y) defined below.

=
7 7 4 5
8 2 3 22
2 6 4 15
5 22 15 12
Y
Suppose we want to access the second and third elements of the fourth row (4
and 7). This means that we are looking for the elements in (Row 4), (Columns 2 and
3). This may be accomplished by setting (i=4) and letting (j=[2 3]). The expression
used to index into Y will then be: >>Y(4,[2 3]).
Suppose we want to index into array Y for the elements shown below in bold.

=
7 7 4 5
3 22
4 15
15 12
8 2
2 6
5 22
Y
The elements we are looking for are located in (Rows 1,2 and 3) and (Columns 3 and
4). To accomplish this, we set the row index i to [1 2 3] and the column index j to [3
4]. The expression then becomes Y([1 2 3],[3 4]). If executed, the answer would be:
Matlab Level 1 Summer 2008



Alexandria Student Branch 31

=
8 2
2 6
5 22
ans

The next step is to access multiple elements as well but in a more flexible
manner. Suppose we want to access the elements bolded in C.

=
1 2 5 6 9 3 1 2
6 9 3 7 8 4 5 6
1 4 5 1 9 3 7 2
7 2 8 4 5
1 7 3 4 3 6 1 3
3 5 2 1 7 3 4 5
8 6 3 9 6 2 7 1
7 1 9 5 3
6 2 8
4 2 8
C

The elements we want to access are located in rows 1 and 5, columns 3,4 and 6. We
might like to extract these elements into another variable T. The syntax required to
accomplish this would be:

T = C ( [ 1 5 ] , [ 3 4 6 ] );

The result of this indexing is shown below.

=
6 2 8
4 2 8
ans


We also know that we may create a vector using linspace or colon notation. The
following example shows how we may access different elements using colon notation
and linspace.
Matlab Level 1 Summer 2008



Alexandria Student Branch 32

=
1 2 5 6 9 3 1 2
6 9 7 4 6
1 4 5 1 9 3 7 2
7 2 8 8 5
1 7 3 4 3 6 1 3
3 5 1 3 5
8 6 3 9 6 2 7 1
7 1 9 8 3
3 8 5
6 2 4
2 7 4
4 2 5
C

We wish to index into rows 1,3,5 and 7 and columns 2,4 and 6 of C. Few possible
expressions to access these elements are:
>>C ( linspace(1,7,4) , 2:2:6 )
>>C ( 1:2:7 , linspace(2,6,3) )
>>C ( [ 1 3 5 7 ] , 2:2:6 )
>>C ( [1 3 5 7 ] , [ 2 4 6 ] )
All these expressions yield the same results.

=
3 8 5
6 2 4
2 7 4
4 2 5
ans


Indexing into Vectors

Indexing into vectors is simpler than indexing into 2-D arrays, because a vector
always has either one row with many columns or one column with many rows.
Therefore, one of the index numbers i or j will always be one, so it is dropped for
short, and we use the other indexing number only to index into the vector. For
instance, T is a vector shown below.
T = [ 4 3 7 8 9 0 6 5 ]
T is a row vector. We can access the 2
nd
element (3) by T(2). The third element is
accessed as T(3). We can access the 3
rd
, 4
th
and 8
th
elements as T ( [3 4 8 ] ). The
same applies to column vectors.



Matlab Level 1 Summer 2008



Alexandria Student Branch 33

Indexing into N-D Arrays

Indexing into 3-D arrays is the same in concept but it uses N index numbers
instead of 2. As an example, if U is a 30-by-30-by-3 array, we may index into the first
5-by-5 sub-arrays of the first 2 layers of the 3 layers using:

U ( 1:5 , 1:5 , 1:2 )


The Colon Index (:)

The colon index is used to cover the whole range of rows or columns. For
instance, we may want to access the bolded elements of M shown below.

=
1 8
4 2
0 9
4 8
5 2
6 0 2
7 3 1
0 6 4
1 7 3
8 0 5
M
We know by now that the syntax used to access these elements has many variations.
One expression using the colon index is:
M ( : , 1:3 )
Matlab reads this expression as the elements in all rows, columns 1,2 and 3 of array
M. The result is shown below.

=
6 0 2
7 3 1
0 6 4
1 7 3
8 0 5
ans


The following example is similar. We want to access the bolded elements in array M.
Matlab Level 1 Summer 2008



Alexandria Student Branch 34

=
1 8 6 0 2
4 2 7 3 1
5 2 8 0 5
0 9 0 6 4
4 8 1 7 3
M
One possible variation of the syntax that may be used to access the required elements
is:
N = M ( [1 H] , : )
Here, H is assumed to have been a vector [4 5] previously defined in the workspace.
Matlab will start evaluating the row and column indices. Rows are indexed by a vector
[1 H]. Matlab will try to evaluate this expression by performing the required
concatenation. If H was not previously defined, Matlab will report an error. After
concatenation, the row index vector will be [1 4 5]. Columns are indexed by a colon,
hence all columns are indexed. The result is shown below.

=
1 8 6 0 2
4 2 7 3 1
5 2 8 0 5
N


Indexing Using end

The word end when used in indexing refers always to the last row or the last
column according to whether it appears as a row index or as a column index. For
instance, consider we have already evaluated array N shown above. The expression L
= N ( [1 end] , end ) accesses elements in the first and last rows, last column. The
result of execution is shown below.

=
1
5
L


Note:
Indexing into arrays is not only used for selecting certain elements of an array but also
use to change the values of certain element of an array.




Matlab Level 1 Summer 2008



Alexandria Student Branch 35

Example:

=
1 8 6 0 2
4 2 7 3 1
5 2 8 0 5
N


If we want to set elements in column 1,3,5 of the second row to zero, we can the
following instruction >>N(2,[1 3 5])=0;
and then the output matrix will be

=
1 8 6 0 2
0 2 0 3 0
5 2 8 0 5
N
















Matlab Level 1 Summer 2008



Alexandria Student Branch 36

Advanced Array Operations using indexing

The operations themselves are not advanced, but the reason behind such naming is
that all advanced applications we will be meeting in Matlab are carried out using basic
operations we have discussed in session 1 in addition to some of the indexing
techniques we have discussed above.


Example : Reordering of an arrays elements
An array M is defined by



=
4 3 2 1
4 3 2 1
4 3 2 1
4 3 2 1
M
Use the appropriate indexing techniques to:
a) Reflect array (M) left-side right,
b) Reflect array (M) upside down,
c) Swap columns 2 and 3 of array (M),
d) Swap rows 1 and 4 of array (M),
e) Shuffle the rows of (M) from [1 2 3 4] to [1 3 4 2] and shuffle the columns of
(M) from [1 2 3 4] to [3 2 4 1].


Solution

a) N = M ( : , [end:-1:1] )
b) N = M ( [4 3 2 1] , : )
c) N = M ( : , [1 3 2 4] )
d) N = M ( [4 2 3 1] , : )
e) N = M ( [1 3 4 2] , [3 2 4 1])

Some of the applications that uses some indexing techniques as shown in the previous
example, will be shown in the next session when dealing with images and sound.






Matlab Level 1 Summer 2008



Alexandria Student Branch 37

Session 2 Tasks:

1- Generate the following sequence:
V=1 4 9 16 25 16 9 4 1
Where V is a sequence of length of 49 elements.

2- For the previous generated sequence V:
a) Add 2 to the last 3 elements.
b) Reverse the order of the last 10 elements.
c) For the first 48 elements, add the elements in the even places to that in
the odd places and store the output in the odd places.

3- Generate the following Matrix:

=
5 0 0 0 5
4 0 0 0 4
3 0 0 0 3
2 0 0 0 2
1 0 0 0 1
x

From Matrix X, generate the following matrices:


=
5 4 3 2 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
5 4 3 2 1
y


=
1 2 3 2 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 2 3 2 1
z

=
5 . 0 100 100 100 10
4 . 0 100 100 100 8
3 . 0 100 100 100 6
2 . 0 100 100 100 4
1 . 0 100 100 100 2
w






Matlab Level 1 Summer 2008



Alexandria Student Branch 38

Session 3
Content
- Dealing with images.
- Dealing with sound.
- Tasks.


Dealing with Images

What is an image?
An image is formed from very tiny elements called picture element or pixel. A pixel
is generally thought of as the smallest complete sample of an image. Each pixel has its
own color. Collecting different pixels with different colors in a certain order, an image is
formed.

Images Representation in Matlab
Images in Matlab are defined as a 3-D Matrix of three layers. An image is defined as an
mn3 matrix. Each element in this matrix represents the color values of a single
pixel. (m) represents the number of rows of the matrix which stands for the number of
the vertical pixels in the picture while (n) represents the number of columns of the
matrix which stands for the number of horizontal pixels in the picture. (mn)
represented the total number of pixels in the whole pictures.
As an example, a 300400 picture is represented in Matlab as a 3004003 matrix.
To define the pixels color, we will focus on RGB color system where every pixel is
given a certain degree of each of the three basic color, Red-Green-Blue. Thats why in
Matlab an image is represented by a three layer matrix where every pixel takes 3
values for the 3 main colors. The first layer contain the red component value of the
pixels, the second contains the green ones and the third contains the blue ones.

Importing Images into Matlab
We can import images in Matlab using the function imread which stands for image
read. Different types of images can be imported into Matlab but we will concentrate on
the widely used JPEG image type. When an image is imported, it is defined as a
variable of type uint8 standing for unsigned integer 8bits, where each color
component is defined in 8bits, having a range of values from 0 to 255. 0 value stands
for no color while value 255 stands for a full color.


Matlab Level 1 Summer 2008



Alexandria Student Branch 39

Example:
A=imread(picture1.jpg);

The previous example loads an image called picture1 of type jpg into a variable A. The
image must exist in the Matlab current directory and must be written between single
quotes. Now A is a 3-D matrix of 3 layers and with the same dimensions of picture1.
Also A is a now a Matlab variable of type uint8.
Now we can do whatever operation we want on A as any 3-D matrix. This will be
shown in Example 1 below.

Viewing Images in Matlab
To display an image in Matlab, we will use the function image. The image is viewed in
a Matlab figure.

Example:
image(A)

Saving Images in Matlab
To save a 3-D matrix as an image, we will use the function imwrite. We will
determine the matrix name and the new picture name and its extension. It will be
automatically saved with the defined name in the Matlab current directory.

Example:
imwrite(A,picture2.jpg)


Example 1: Linear Image Transformations
Load an image into Matlab using imread. View this image using image. Follow it by
>>axis image to correct the aspect ratio.
a) It is required to view the red intensity, the green intensity and the blue intensity
of the image separately.
i) Write down Matlab instructions to produce a replica of the original image
variable.
ii) Write down Matlab instructions to zero the green and blue intensities
(second and third layers) of the replica.
iii) Use the image function followed by >>axis image to preview the
replica.
iv) Repeat steps i) through iii) but to view the second (green) intensity
alone.
v) Write down Matlab instructions to produce an array of zeros having the
same size as the original image.
vi) Write down Matlab instructions to copy the contents of the third layer of
the original image to the third layer of this array of zeros.
Matlab Level 1 Summer 2008



Alexandria Student Branch 40

vii) Use the image function followed by >>axis image to display the
array.
viii) Use the imwrite function to write the three intensity layers to JPG files.
b) It is required to reduce the image size by reducing the number of pixels. Write
down Matlab instructions to subset pixels from the image according to the shown
interleaving rule.



c) Write down Matlab instructions to reflect the reduced image left-side-right.
d) Use the imwrite function to register the reduced and reflected image to a JPG
file.
e) Convert this colored image to gray scale.

Solution

a) The syntax is as follows: >> A=imread(tif1.jpg); image(A); axis image;
The result of execution will be the display of an image in a figure window as shown
below.
Matlab Level 1 Summer 2008



Alexandria Student Branch 41



i)B=A;
ii) B(:,:,[2 3])=0;
iii) image(B)


Matlab Level 1 Summer 2008



Alexandria Student Branch 42

iv) C=A; C(:,:,[1 3])=0; image(C);

v) D=zeros(size(A));
vi) D(:,:,3)=A(:,:,3);
vii) D=uint8(D); image(D);

Matlab Level 1 Summer 2008



Alexandria Student Branch 43

viii) imwrite(B,rlayer.jpg); imwrite(C,glayer.jpg); imwrite(D,blayer.jpg);

b) Reduction by interleaving of image pixels may be carried out using the
command >> E = A ( 1:2:461 , 1:2:699 , : );
Note that the resulting image will appear pixilated if viewed at a size larger than
supported by its new number of pixels. He new image is viewed at same pixilation as
the old image when its height and width are half those of the old image.










Matlab Level 1 Summer 2008



Alexandria Student Branch 44

c) The reflection may then be carried out by an operation we have done before.
Since the required reflection is right-to-left, the column index should be swapped
around. The appropriate command is:
>> E( : , 1:350 , : ) = E ( : , 350:-1:1 , : ) ;



The modified and reduced image may then be registered to a JPG file using the
command: >> imwrite ( E , mrimage.jpg);

d) To convert the image to gray scale, the three layers must have the same
degree of colors; that means that the three layers must be equal.
This can be done by equating layer 2&3 to layer 1 or equating layer 1&3 to layer
2 or equating layer 1&2 to layer 3. The difference between the previous
techniques is in the degree of the gray scale. Try each of the following commands
and notice the difference in the output image.
>>im1=A(:,:,[1 1 1]);image(im1)
>>im2=A(:,:,[2 2 2]);image(im2)
>>im3=A(:,:,[3 3 3]);image(im3)


Matlab Level 1 Summer 2008



Alexandria Student Branch 45

Dealing with Sound

Working with sound is a simple process in Matlab. A sound stream may be represented
inside the computer as a set of vector of samples. These samples are played at a
certain sample rate by the sound card to emulate the sound. Since we are dealing with
stereophonic sound, the signal going to the left speaker is in general different than the
signal going to the right speaker. Hence, stereophonic sound may be represented as a
matrix consisting of two column vectors. The left vector is the left channel signal and
the right vector is the right channel vector.

A sound stream in a wave-file (filename.wav) maybe imported as a matrix into the
Matlab working environment using the wavread function. Its syntax is as follows:

>>[A,fs]=wavread(filename);

This instruction searches for the wave file specified by filename over the Matlab
search path, and then returns the sample vectors in matrix A and the value of the file
sample frequency in fs.

During and after the sound stream, we will need to preview it before it is saved back to
wave file. Any vector or two column matrix in Matlab may be previewed using the
sound function . The syntax is as follows:

>>sound(A,fs)

This instruction plays the vector or matrix A at the sample rate specified by fs.

After we finish processing the sound stream, we will need to register it back to a
stand-alone file format. We can convert a vector or two column matrix in Matlab to a
wave file using the wavwrite function. Its syntax is as follows:

>>wavwrite(A,fs,nbits,filename.wav);

This instruction uses n bits to encode each sample of A into the file specified by
filename and sets the file sample frequency to fs.







Matlab Level 1 Summer 2008



Alexandria Student Branch 46

Example 2: Piece-wise Operations on a Sound Vector
Use the wavread function to load test sound file tsf1.wav into the Matlab
workspace. Note that the sound file loads into the workspace as a 2-by-N matrix. This
matrix can be viewed as 2 1-by-N vectors, one for each of the left and the right audio
channels. N is the number of samples of the audio file. If you have invoked wavread
with two output arguments, then you will have also loaded the sampling rate fs of the
audio file. The number of samples N is the product of the sampling rate in samples per
second and the file duration in seconds.
a) Given the sampling rate and the number of samples of this audio file, how long is
its playback duration?
b) It is required to scale up the first third of the sound stream to four times its
original values, leave the second third unchanged and scale up the last third of
the audio file to double its original values by directly manipulating the sample
values. Write down Matlab instructions to carry out this editing, then use the
sound function to play the modified audio stream.
c) Use the wavwrite function to generate a wave file that contains the modified
audio stream.

Solution
a) The wave file may be loaded into the Matlab workspace using the command
(>>[A,fs]=wavread(tsf1.wav);). The number of samples for the left or the right
channel is 260331 samples. The sampling rate is 44100 samples per second.
Hence the total audio stream duration is 260331 / 44100 = 5.9032 seconds.
b) The first third of the sound stream is held by samples 1 through 86777. The last
third of the sound stream is held by samples 173555 to 260331. Whenever we
are to edit a loaded file, it is better to replicate the variable (A in our case) and
to edit the replica in order to avoid needing to reload the file. Here, B is a replica
of A. Hence, we may use the commands
>>B(1:86777,:)=4*B(1:86777,:);
>>B(173555:260331,:)=2*B(173555:260331,:);
>>sound(B,fs)
c) The syntax is as follows: >>wavwrite(B,fs,tsfed.wav);










Matlab Level 1 Summer 2008



Alexandria Student Branch 47

To generate a single tone sound, we need first to define the time vector for the
required duration with number of time samples in each seconds equals the required
sampling rate.

Example 3: Generation of a single tone audio file
We need to generate three single tone files, each for 3 seconds with a sampling
rate of 22050 samples per second. The first one has a frequency of 250 Hz, the
second with frequency of 500 Hz and the third with frequency of 1000 Hz.

Solution
>>fs=22050;
>>t=linspace(0,3,3*fs);
>>s1=sin(2*pi*250*t);
>>sound(s1,fs)
>>s2=sin(2*pi*500*t);
>>sound(s2,fs)
>>s3=sin(2*pi*1000*t);
>>sound(s3,fs)

























Matlab Level 1 Summer 2008



Alexandria Student Branch 48

Session 3 Tasks

Task 1:
Produce the following image with the defined colors.


Red

White

White

Black

Green

White

Black

Black

Blue

The image dimension is 300300 with each color box of dimension 100100.

Task 2:
Produce the following image with the defined colors.












The image dimension is 600800 with each color box of dimension 60800.



Matlab Level 1 Summer 2008



Alexandria Student Branch 49

Task 3:
From the 1
st
image, generate the 2
nd
one.


Task 4:
Write a short Matlab code to generate the following image, display it and save it in your current
directory with the name task4_image.jpg.











Degradation of
degrees of Green
color
Degradation of
degrees of Green
color
Dark
Green
Light
Green
Matlab Level 1 Summer 2008



Alexandria Student Branch 50

Task 5: Step Frequency Scan
We wish to test the performance of an audio signal at different frequencies. This
can be done by playing a sound file that scans the required frequencies. We want to
generate this file knowing the following information:
1. The total file duration is 8 seconds.
2. The sampling rate is 22050 sample/sec.
3. The file is monophonic.
4. The scan is discrete and should cover the following frequencies each for 1
second:
20 Hz 32 Hz 63 Hz 125 Hz 500 Hz 1000 Hz 2000 Hz 3000 Hz

Task 6: Continuous Frequency Scan
Instead of using step scan, we will use a continuous scan with the following
specifications:
1. The total file duration is 10 seconds.
2. The sampling rate is 44100 sample/sec.
3. The file is stereophonic.
4. The scan should cover the frequencies from 20 Hz to 4 KHz continuously.

Task 7: Generating Siren Signal
We want to generate a siren signal with the following requirements:
1. The signal will continuously scan frequencies from 500 Hz up to 2500 Hz in 1
second. This will be repeated to have a total duration of 12 second.
2. The sampling rate is 22050 sample/sec.
3. The file is stereophonic.


















Matlab Level 1 Summer 2008



Alexandria Student Branch 51

Session 4
Content
- Using Matlab functions,
- Some important Matlab functions,
- Mathematical functions,
- 2-D plotting,
- 3-D plotting,
- Tasks.

Using Matlab Functions

In Matlab, a function is a module to which one or more input arguments are passed,
and from which one or more output arguments are awaited.



Input Arguments Function Output Arguments




Some functions have one input argument, others have multiple input arguments.
Some functions have one output argument, others have multiple output arguments.
Most functions that have multiple input/output arguments support variable
input/output arguments. This means that you do not have to supply all input
arguments and you do not have to call the function with all of its output arguments. If
you decide not to supply all of the functions input arguments, the unsupplied input
arguments will take default values defined in the function itself.
If you decide not to supply some of the input arguments, there might be some
confusion concerning which input arguments you intended to enter. Input arguments
are sequenced according to their importance in determining the functions behavior. If
you decide to drop 2 input arguments and pass in only 3, Matlab shall assume that you
have passed in the first 3, and will assign default values to the 2 you didnt enter.
You can decide to call a function with all or some of its output arguments. A
functions output arguments are sequenced according to their importance. The most
important output argument comes first. If you call a function with only 2 of its 3 output
arguments, the first two of its output arguments will be supplied.
Matlab Level 1 Summer 2008



Alexandria Student Branch 52

As an example, consider the wavread function we have used before. This
function reads a wave file into the Matlab workspace. The complete function syntax is:
>> [Y,Fs,Nbits] = wavread ( filename.wav ) ;
The function accepts only 1 input argument, which is the file name. The function
has 3 output arguments and supports variable output arguments.
The following command returns only the sample values, but you have no idea about
the sampling rate the file uses.
>> Y = wavread ( filename.wav ) ;
If you want to get the sample values as well as the sampling rate used, we must
call wavread with two output arguments. In the following command, the samples will
be stored in a matrix A and the sampling rate value will be stored in B.
>> [Y,Fs] = wavread ( filename.wav ) ;
If we want to know the number of bits used to encode every sample in the wave
file, we must call wavread with 3 output arguments, even if we are not interested in
knowing the sample rate.

Some Important Matlab Function

Here we will list some of the important Matlab functions and briefly discuss what
they are used for.

Name Purpose
clc Clear Command Window Display Area
clear Delete some or all variables in the workspace
format Control number display format
help Display function help
lookfor Search for functions by words in their help
length Length of a vector, or maximum dimension of a matrix
size Size of a matrix
numel Number of elements in an array
ndims Number of dimensions of an array
cross Vector cross product
dot Vector dot product
end Last index
find Find indices of elements satisfying a certain condition
min Minimum in a vector or minima in the columns of a matrix
max Maximum in a vector or maxima in the columns of a matrix
det Determinant of a matrix
rank Rank of a matrix
inv Inverse of a matrix
Matlab Level 1 Summer 2008



Alexandria Student Branch 53

Array Generation Functions

Name Purpose
zeros Generates a matrix of zeros
ones Generates a matrix of ones
eye Generates an Identity matrix
magic Generates a magic square matrix
linspace Generates a vector of uniformly distributed values
logspace Generates a vector of logarithmically distributed values
meshgrid Generates a base grid for 3-D plots
rand Generates a matrix of randomly chosen values between 0 and 1
randn Generates a matrix of normally distributed values (Mean 0,
Variance 1)


Mathematical Functions

Almost all of the mathematical functions we will need in Matlab are single input /
single output argument functions. This means that we will only supply the number(s)
for which we want to compute the sine or cosine or whatsoever, and we will only await
the value(s) of the sine or cosine of the input number(s).
In all mathematical functions, the single input argument may be a scalar (single
number), a vector or a matrix. If the input is a scalar, the output will simply be a
scalar representing the sine or cosine of the input number. If the input is a vector of
numbers, the output will be a vector of the sines or cosines of the numbers in the input
vector. If we want to evaluate the function over a range of input values, we usually
construct an input vector covering that range using F:S:L notation or using the
linspace function.
Example:
>> t = linspace ( -pi , pi , 100); % 1-by-100 vector of points from pi to pi
>> y = sin ( 8*pi*t); % returns a 1-by-100 vector of the sines of the values

Trigonometric Functions
Name Purpose
sin Sine (Input considered to be in Radians)
cos Cosine (Input considered to be in Radians)
tan Tangent (Input considered to be in Radians)
csc Cosecant (Input considered to be in Radians)
sec Secant (Input considered to be in Radians)
Matlab Level 1 Summer 2008



Alexandria Student Branch 54

cot Cotangent (Input considered to be in Radians)
asin Inverse Sine (Output is in Radians)
acos Inverse Cosine (Output is in Radians)
atan Inverse Tangent (Output is in Radians)
acsc Inverse Cosecant (Output is in Radians)
asec Inverse Secant (Output is in Radians)
acot Inverse Cotangent (Output is in Radians)
sind Sine (Input considered to be in Degrees)
cosd Cosine (Input considered to be in Degrees)
tand Tangent (Input considered to be in Degrees)
cscd Cosecant (Input considered to be in Degrees)
secd Secant (Input considered to be in Degrees)
cotd Cotangent (Input considered to be in Degrees)
asind Inverse Sine (Output is in Degrees)
acosd Inverse Cosine (Output is in Degrees)
atand Inverse Tangent (Output is in Degrees)
acscd Inverse Cosecant (Output is in Degrees)
asecd Inverse Secant (Output is in Degrees)
acotd Inverse Cotangent (Output is in Degrees)

Hyperbolic Functions

Name Purpose
sinh Hyperbolic Sine
cosh Hyperbolic Cosine
tanh Hyperbolic Tangent
csch Hyperbolic Cosecant
sech Hyperbolic Secant
coth Hyperbolic Cotangent
asinh Inverse Hyperbolic Sine
acosh Inverse Hyperbolic Cosine
atanh Inverse Hyperbolic Tangent
acsch Inverse Hyperbolic Cosecant
asech Inverse Hyperbolic Secant
acoth Inverse Hyperbolic Cotangent






Matlab Level 1 Summer 2008



Alexandria Student Branch 55

Exponential & Logarithmic Functions

Name Purpose
exp Exponential (e
x
)
log Natural Logarithm ln(x)
log2 Logarithm to the Base of 2
log10 Logarithm to the Base of 10 (Common Logarithm)
sqrt Square root
nthroot Nth root
nextpow2 The next power of 2 (important in binary applications)

Complex Numbers

Name Purpose
real Real part of a complex number
imag Imaginary Part of a complex number
abs Absolute value (Magnitude) of a complex number
angle Angle (Phase) of a Complex Number
conj Complex conjugate of a complex number

- Note:
Matlab uses the key letters i and j to define the imaginary unity by default.

Rounding and Remainder

Name Purpose
fix Round a non-integer towards zero
floor Round a non-integer down
ciel Round a non-integer up
round Round towards the nearest integer
mod or rem Modulus or Remainder after division (close to each other)

Discrete Mathematics

Name Purpose
factorial Factorial of a number
gcd Greatest Common Denominator of 2 numbers
lcm Least Common Multiple of 2 numbers
nchoosek N combination k
perms N permutation k
primes Generates a list of prime numbers

Matlab Level 1 Summer 2008



Alexandria Student Branch 56

Polynomials and Curve Fitting

Name Purpose
polyfit Find the coefficients of a polynomial that best fits between a set
of points
polyval Evaluate a polynomial given its coefficients over a range of
values
spline Interpolate to go from one range to another
polyder Polynomial differentiation
polyint Analytic polynomial integration































Matlab Level 1 Summer 2008



Alexandria Student Branch 57

2-D Plotting

Producing a 2-D plot consists of 2 main steps: Preparing the data to be plotted
and invoking the plot command.

Preparing Data to be Plotted

Preparing the plot data consists of two steps. The first is to prepare the base
vector (x-axis) values, and the second is to prepare the y-axis values. For example if
we want to plot sin(2*t) from t= -pi to pi, we start by defining the vector t containing
the x-axis values of the plot points.
>> t = linspace (-pi , pi , 100) ;
Secondly, we compute the vector y containing the y-axis values of the points to be
plotted.
>> y = sin ( 2*t ) ;

The Plot Command

The plot command syntax is described below.
>> plot ( vector1 , vector2 , line specification string )
The plot command operates as follows. It plotting by marking the position of the points
on the graph. Every point is defined by an x coordinate in vector1 and a y coordinate in
vector2. The x coordinate of the first point is vector1(1) and its y coordinate is
vector2(1). The x coordinate of the nth point is vector1(n) and its y coordinate is
vector2(n). Then, Matlab connects every point with the point before it and the point
after it using straight lines.
If the points are close enough to one another, the breaking of straight lines at
their joints will be invisible and the plot will appear smoothly curved. You can repeat
the example using linspace with 10 points instead of 100 to see the difference.
The appearance of the curve can be controlled through the line specification
string. The line specification string defines three things:
The line color,
The line type,
The point marker shape.

For example, a line specification string r--p' means that the line color is red, the line is
dashed and that the marker shape is pentagonal.





Matlab Level 1 Summer 2008



Alexandria Student Branch 58

Line Colors:
Line Color Letter
White w
Yellow y
Red r
Green g
Blue b
Cyan c
Magenta m
Black k
Line Types:
Line Type Letter
Solid -
Dashed --
Dotted :
Dash-dotted -.
No line
Marker Shapes:
Marker Shape Letter
Circular o
Square s
Pentagonal p
Hexagonal h
Diamond d
Triangular (down) v
Triangular (left) <
Triangular (right) >
Cross x
No Marker

If you specify no color, Matlab will use blue by default. If you specify no line
style, Matlab will use no lines by default. If you specify no marker, Matlab will use no
point marker by default. If you specify no line specification string at all, Matlab will use
blue solid lines and no point markers by default.
For example, if we want to plot the function y=sin(2*t) using a green dotted line
with cross markers, the plot command will be
>> plot ( vector1 , vector2 , g:x)
Matlab Level 1 Summer 2008



Alexandria Student Branch 59




Plotting More than One Curve On the Same Graph

If you try to plot a cosine curve after the previous sine plot, you will realize that
the cosine curve will replace the sine curve. The sine curve will be lost. What about if
we want to plot many curves on the same graph?
The hold on instruction tells Matlab to hold all current plots on the graph and
superimpose any new curve onto the existing ones. Typing >> hold on
lets Matlab hold the existing curves. Any plot command issued after hold on will not
cause Matlab to delete old plots.
To quit holding current plots, type
>> hold off
Matlab Level 1 Summer 2008



Alexandria Student Branch 60

This will let Matlab delete old curves starting from the next plot command. The hold
state is off by default. Typing >>hold alone toggles the hold state. The following is an
example of 3 superimposed curves.



- Note:
We can also plot more than one curve on the same figure by another method. This can
be done by entering the functions we want to plot in the same command. This can be
done as follows: >>plot(x1,y1, ,x2,y2, ,)

- Note:
To plot a curve on another figure, you can use the function figure.
>>figure
Matlab Level 1 Summer 2008



Alexandria Student Branch 61

Also we can define the figure number,
>>figure(2)
>>figure(6)
- Note:
To clear a figure, you can use the function clf.

Conditioning Plots

Inserting Captions, Titles, Legends and Labels

We may use the Insert menu in the figure window to add captions, titles, labels and
legends. The first figure on the next page shows the entries in the Insert menu. The
figure after it shows the same plot shown above but with titles, captions, arrow text
and a legend box.

Matlab Level 1 Summer 2008



Alexandria Student Branch 62



The same can be done using command window by using some Matlab functions.
Example:
>>title(Multiple plots on a single graph) %title is used to insert a graph title
>>xlabel(times in second) %xlabel is used to insert a label for x-axis
>>ylabel(value of the function) % ylabel is used to insert a label for y-axis
>>legend(sin(2t) , cos(2t) ) %legend is used to insert legend box

Using the LaTex Interpreter

The LaTex interpreter is a tool used for writing Greek and Latin symbols on
figure windows as well as writing superscripts and subscripts.
The following table shows some of the LaTex interpreter syntax.





Matlab Level 1 Summer 2008



Alexandria Student Branch 63

Sequence Symbol Sequnce Symbol
\alpha o \phi
o
\beta
|
\chi
;
\gamma

\psi
v
\delta o \omega e
\epsilon c \Gamma I
\zeta
.
\Delta A
\eta
n
\Theta O
\theta u \Lambda A
\iota i \Xi
\kapa k \Pi H
\lambda \Sigma

\mu
u
\Upsilon Y
\nu v \Phi u
\xi
c
\Psi +
\pi t \Omega O
\rho
p
\int
\sigma o \bf bold
\varsigma . \it italic
\tau t \sl oblique
\upsilon u \rm normal
^ superscript _ subscript

In the following figure, the following LaTex commands were used.
In the X-Caption: \tau
In the Y-Caption: Ae^{-\omega\tau}cos(\omega\tau)

Matlab Level 1 Summer 2008



Alexandria Student Branch 64



Showing / Hiding Grid Lines

The commands >>grid on and grid off can be used to show and hide grids
respectively.

Controlling Figure Color

The gray shade behind the axis box may be changed to white by entering the
selection mode. You can enter the selection mode by clicking on the mouse-pointer
shaped button on the toolbar in the figure window. Then, double click anywhere on the
figure outside the axis box. A small property panel will open. Inside you will find the
background color selection.

Matlab Level 1 Summer 2008



Alexandria Student Branch 65



Controlling Axis Limits and Grid Lines

By entering the selection mode, and then double clicking anywhere over the axis
box, but not over one of the curves, you get a property display like the one shown
above. There you can find means to control axis limits, axis colors, aspect ratio,
background color of the axis box, as well as properties related to grid lines.



The same can be done using the function axis
>>axis([Xstart Xend Ystart Yend])

Using subplot

The function subplot allows you to create multiple axis boxes on the same
figure. The following shows a figure created using subplot.

Matlab Level 1 Summer 2008



Alexandria Student Branch 66






















Matlab Level 1 Summer 2008



Alexandria Student Branch 67

3-D Plots

As with 2-D plotting, 3-D plotting consists of 2 main steps: preparing the data to
be plotted and invoking the plot command. We have two types of 3-D plots: 3-D
surface plots and 3-D line plots.

3-D Surface Plots

Preparing Data for 3-D plots

In 2-D plots, we used to plot 1-D signals, that is signals of 1 independent
variable only such as f(t) against t. We used to choose a set of values of t at which f(t)
is evaluated and at which the plot points will be placed. In 3-D plotting, we have 2
independent variables (x) and (y). We have a third dependent variable (z) where
z=f(x,y).
In order to plot z against x and y, we have to start defining the values of x and y
over which the plot points will appear. In this case, we have to prepare not a vector,
but a grid as shown below.



Matlab Level 1 Summer 2008



Alexandria Student Branch 68

This grid is created using a special function called meshgrid. Its syntax is:
>> [x,y] = meshgrid ( xvector, yvector ) ;

xvector is a vector containing the values of x of the grid and yvector is a vector
containing the y values of the grid. In the figure shown above, the x and y values are
taken the same. These values are [-5 -4 -3 -2 -1 0 1 2 3 4 5]. These are 11 values.
The output arguments x and y will be two 11-by-11 matrices. Every element in x or in
y defines the x or y coordinate of the corresponding point in the 11-by-11 grid. You
dont see the grid. The figure above is only to illustrate the concept of the grid created.

The next step is to compute the values z. If we write
>> z = exp(-0.2*x)*exp(-0.1*y) ;
the plot will be totally incorrect. The reason behind this is that x and y are matrices, so
exp(-0.2*x) and exp(-0.1*y) are also matrices. If we write the function stated above,
Matlab will matrix-multiply these two matrices, thus producing results other than
those we wanted. We want to multiply exp(-0.2*x) by exp(-0.1*y) for every point
knowing its x and y coordinates. That is we want to carry out an element-by-element
multiplication (array multiplication). Thus the correct syntax will be
>> z = exp(-0.2*x) .* exp(-0.1*y) ;

Note that if the lengths of the x and y vectors were different, Matlab wont have been
able to carry out the matrix multiplication. It would have issued an error message
saying that Inner matrix dimensions must agree. This is nothing but the condition for
matrix multiplication.

3-D Surface Plot Commands

We have two surface plot commands. The first is called mesh and the second is
called surf. In both case, the plot command accepts the x,y and z matrices as input
arguments. That is, their syntax is:
>> mesh ( x , y , z )
>> surf ( x , y , z )
Both commands will start by going to the grid points defined by the x and y matrices
and then moves in the z direction by the values in the z matrix elements corresponding
to those points. Both commands will position those points properly in the 3-D space.
So what is the difference between the two?
After positioning the points in space, the mesh command will connect every point
with its neighboring points using lines. The result is a meshed surface, i.e. the
surface appears as if it silk-wired. The following shows a mesh plot of the function
z = exp(-0.2*x) .* exp(-0.1*y).

Matlab Level 1 Summer 2008



Alexandria Student Branch 69



The surf command will do the same, but it will then start color-filling the areas
bounded by the mesh lines. The figure below shows a surf plot of the same function.

Matlab Level 1 Summer 2008



Alexandria Student Branch 70

After invoking the surf command, we can enhance the color shading of the resulting
surface by writing the instruction:
>> shading interp
The following figure shows the same surface after this shading interpolation
command.



3-D plots may be rotated, panned and zoomed if you would like to condition its
appearance.

Matlab Level 1 Summer 2008



Alexandria Student Branch 71

3-D Line Plots

3-D line plots are curves that exist in 3-D space, i.e. curves that do not
necessarily lie in the x-y plane. 3-D line plots are carried out using the plot3 function.
This function is very similar to the plot function, but you specify a third vector to define
the z coordinates of the plot points. Line specification is identical to that in 2-D line
plots using plot.
Example: A Helix
>>t = 0:pi/50:10*pi;
>>plot3(sin(t),cos(t),t);


Matlab Level 1 Summer 2008



Alexandria Student Branch 72




Matlab Level 1 Summer 2008



Alexandria Student Branch 73

Session 4 Tasks

Task 1: Best Fits and 2-D Plotting

In an experiment to determine the relation between the input current and output
power of a light emitting diode (LED), the following table of results was obtained.
Input Current (mA) Output Power ( u W)
0.0 0.00
1.0 2.9
2.0 6.2
3.0 8.8
4.0 12.1
5.0 14.9
6.0 18.2
7.0 21.0
8.0 24.4
9.0 27.1
10.0 29.7

It is required to fit a straight line between the points using the polyfit and polyval
functions, then plot a labelled graph of the experimental points and the corresponding
best fit line.

Task 2:
Plot the following functions on the same figure using subplot

i) y=
x
x sin
ii) y= x
x
+

2
) 1 (
1

iii) y=
4
1
2
2

+
x
x
iv) y=
2
1
2
3
1
) 4 (
2 ) 10 (
x
x



where 10 0 s s x


Task 3: 3-D Plots

Draw the 3-D surface corresponding to the function z(x,y)=cos(2t x)sin(2t y)
over the values of x and y ranging from 3 to 3. Use the surf command with
interpolated shading.


Matlab Level 1 Summer 2008



Alexandria Student Branch 74

Task 4: 3-D Plots
Draw the 3-D surface corresponding to the function z(x,y)=
) ( 2
2 2
y x
xye
+
over
the values of x and y ranging from 2 to 2. Find the values and locations of the
maximum & minimum points of this function.
Hint: Use max, min, find.





































Matlab Level 1 Summer 2008



Alexandria Student Branch 75

Session 5

Content
Part 1: Program Flow Control
Loop Control
Conditional Control
Error Control
Part 2: Programming and Debugging M-Files
Creating New M-Files
Opening Existing M-Files
Script and Function M-Files
Debugging M-Files
Additional Information
Tasks.

Part 1: Program Flow Control
Loop Control
a. For Statements
Syntax


for i= [vector]
.
. (Block of Code)
.
end




Matlab Level 1 Summer 2008



Alexandria Student Branch 76

Mechanism

The for statements provides loop control. The statement operates as follows. In
the opening statement, a variable i and a vector of values for i are defined. Matlab
starts by assigning the first value in the vector to i, and then executes the block of
code bounded between the for and end keywords. Then, flow goes back to the for
and the process is repeated for the second value in the vector. This is repeated until all
values in the vector are covered. The condition of termination here is that there are no
more new values in the vector.
Note that the for statement requires previous knowledge of the values that will
be used in looping, as the vector of values must be constructed before we enter the
loop.
Examples:


for i= [1 5 2 7]
i
end


for i= 1:10
disp(Hello)
end


for i= 9:-1:0
pause(1)
disp([num2str(i) seconds left.])
end
- Note:
i. The function pause is used to insert a wait state of duration in seconds defined
as an input to the function.
ii. The function disp is used to display a user-defined string in the command
window. Its input must be a string.
iii. The function num2str, standing for number to string, is used to convert a
numeric variable to a string that can be used in string operations. The opposite
function also exists. str2num is used to convert a string to a number that can
be used in mathematical operations.



Matlab Level 1 Summer 2008



Alexandria Student Branch 77

Examples
It is required to plot sin x nt where 1 1 s s x and n=1,2,3,.,8 on the same figure
using subplot.
>>x=-1:0.05:1;
>>for n=1:8
subplot(4,2,n)

plot(x,sin(n*pi*x)
title([sin(2pi num2str(n) )])
end

b. While Statements
Syntax

while expression
.
. (Block of Code)
.
end

Mechanism

The while statement operates as follows. When it is entered, expression is
evaluated. If it evaluates to 1, the block of code will be executed. After finishing the
last command in the block, Matlab will go back to the expression and re-evaluate it. If
it still evaluates to 1, Matlab will start executing the block of code once again. This will
be repeated until expression evaluates to zero. In this case only will Matlab exit the
while loop.

Example:

while 1
pause(1);
disp(This loop will go on forever);
end
% This is an infinite loop, meaning that Matlab can never exit it, because %the
expression will always evaluate to 1.


Matlab Level 1 Summer 2008



Alexandria Student Branch 78

Example:
It is required to generate a sequence as follows:
2 2 2 2
. .......... 3 2 1 n s + + + + =
Such that the value of s doesnt exceed a certain value entered by the user.

>>s=1;n=2;
>>m=input(Enter max value of the sequence: );
>>while (s+n^2)<m
s=s+n^2;
n=n+1;
end

Note:
The function input is used to get inputs from keyboard after displaying a text telling
the user to wanted input.

Note: Using continue

The keyword continue when reached inside a loop causes execution of the
current pass through the loop to end and the execution of the next pass through the
loop to begin.
Note: Using break

The keyword break when reached inside a loop causes termination of the whole
loop and passes control to the instruction after the loops end word.









Matlab Level 1 Summer 2008



Alexandria Student Branch 79

Conditional Control
a. If Statements
Syntax

if expression1
.
. (Block 1 of Code)
.
elseif expression 2
.
. (Block 2 of Code)
.
elseif expression 3
.
. (Block 3 of Code)
.
else
.
. (Block 4 of Code)
.
end


Mechanism

The if statement operates as follows. The if keyword is followed by an
expression. Matlab evaluates the expression. If the expression evaluates to 1 (true or
non-zero), block 1 will be executed and then Matlab will go to end and the if
statement will be exited. If expression 1 evaluates to 0, Block 1 is skipped, and Matlab
goes to the first ElseIf. Expression 2 is evaluated. If it evaluates to 1, Block 2 will be
executed and then Matlab will go to end and the if statement will be exited. If
expression 2 evaluates to 0, Block 2 will be skipped. If none of the if or elseif
expressions evaluate to 1, Matlab reaches the else part, which doesnt have a test
expression. Therefore Block 4 will be executed.
Note that the elseif and else parts are optional. The if statement may consist
of an if only, if and else only, if and elseif only, or all three.



Matlab Level 1 Summer 2008



Alexandria Student Branch 80

Example:
if a=1
b=0
end
(This will cause an error because a=1 is an operation not a relational expression)

if a==1
b=0
end
Example:
It is required to write a program that allows a maximum of 50 authorized users
to enter a room after entering the correct password.

>>guests = 0;
>>while (guests < 50)
access=input(please enter your access code);
if access==3714
open_the_door;
pause(2);
close_the_door;
guests=guests+1;
else
disp(Incorrect access code! Please retry.);
end
end












Matlab Level 1 Summer 2008



Alexandria Student Branch 81

b. SwitchCase Statements
Syntax

switch expression
case value1
.
. (Block 1 of Code)
.
case value2
.
. (Block 2 of Code)
.
case value3
.
. (Block 3 of Code)
.
otherwise
.
. (Block 4 of Code)
.
end

Mechanism

Switch Case Statements operate as follows. The expression after the switch
keyword is evaluated and the result is compared to the values after the case words. If
the result matches any one of these values, the block of code following that case will
be executed. If none of the values after the case words matches the result of the
expression, the block of code after the otherwise word is executed.
The otherwise part is optional. Also, the switching value may be a number,
character or a string.

Example
It is required to calculate the number of network interface cards required to build
a network. The user specifies the number of devices and the network topology used,
and Matlab should return the total number of network interface cards (NICs) required
to implement the network. If N is the number of computers on the network, then the
number of NICs required to implement the connections will be N(N-1) for a mesh
Matlab Level 1 Summer 2008



Alexandria Student Branch 82

topology, 2N for a ring topology, N for a bus topology and N for a star topology. Here
is the code to calculate the number of required NICs.

>>topology=input(enter Network topology: ,s);
>>N=input(Enter No. of Nodes: );
>> switch topology
case mesh
NICs=N*(N-1);
case ring
NICs=2*N;
case star
NICs=N;
case bus
NICs=N;
otherwise
disp(Sorry. Unknown Network Topology)
end

Note:
The second input s in the function input is use when the user inputs a string not a
number.











Matlab Level 1 Summer 2008



Alexandria Student Branch 83

Error Control
TryCatch Statements
Syntax

try
.
. (Block 1 of Code)
.
catch
.
. (Block 2 of Code)
.
end


Mechanism

The try catch statement operates as follows. It tries to execute block 1 of code.
If the code is executable without errors, it is executed. If an error occurs, execution of
block 1 is aborted and block 2 of code is executed and no matlab errors will appear.
Try catch statements are usually used to detect and report errors done by someone
who uses your program. See the following example.

Example:
This program is used to display error message when no image with the defined
name exists.
>>try
Im=imread(picture1.jpg);
catch
disp(error, Image is not found)
end






Matlab Level 1 Summer 2008



Alexandria Student Branch 84

Part 2: Programming and Debugging M-Files
Creating New M-Files

There are three ways to create a new M-File. The first way is to go to the file
menu in Matlabs main window. In the file menu, choose New -> M-File. The second
way is to choose the New M-File icon in the toolbar as shown below.


The third way is to write (>>edit) at the command prompt. The word edit alone opens
the M-File editor to a new empty untitled M-File.


Opening an Existing M-File

There are many ways of opening an existing M-File. Ivf you are outside Matlab,
you can double click on the files icon. If you are inside Matlab, you can go to File ->
Open and then select the desired file. A quicker way is to write (>> edit filename) at
the command prompt, where filename is the name of the file you want to open.



Script and Function M-Files

When we look at M-Files from outside, they all look the same. However, when we
look at the code written inside, we find that an M-File may actually be of one of two
types; either a script M-File or a function M-File. What is the difference?

A script M-File is simply a sequence of instructions, or a routine, to execute,
without the need to pass in input arguments or to pass out output arguments from
these instructions. We can imagine a script M-File as a paper of commands passed by a
boss to define a certain blind routine which an employee must execute.

Matlab Level 1 Summer 2008



Alexandria Student Branch 85

A function M-File is simply a piece of code that accepts some input arguments,
carries out some processing using these input arguments and produces some output
arguments as a result of the processing. A function M-File has markable terminal
behavior. This means that we may understand a function M-File as a block having
input ports and output ports, and an internal algorithm that defines the process to be
carried out. In this sense, we can appreciate why function M-Files play the main role in
complicated programs. Function M-Files as blocks may be interconnected to achieve
any desired complex function using simpler functions. Also, the interconnection may be
controlled using program flow.

We can program a function M-File to operate as a script M-File by defining no
input nor output arguments. However, we cant program a script M-File to operate as a
function M-File, because script M-Files lack the concept of input and output.

I. Programming and Running Script M-Files

Programming and running Script M-Files is a very simple task. The following
steps illustrate the process.
1. Create a new M-File.
2. Write a sequence of Matlab instructions such as the following.
for u=9:-1:0
pause(1);
disp([num2str(u) seconds left])
end
3. Save the M-File. For instance, call it countdown. This saves your script in a file
called countdown.m.
4. Try running the script from the M-File editor using the run icon.
5. Try running the script from the command prompt by typing (>>countdown).


II. Programming and Running Function M-Files

The main steps of programming function M-Files are identical to those of
programming script M-File. These are writing and then saving the M-File. However, a
function M-File always starts by a very significant line called the declaration line. The
declaration line takes the following format:

function [OP1, OP2, , Opn] = functionname(IP1, IP2,, Ipn)

Very important to note is that a functions declaration line shall NEVER end with a
semicolon.
Matlab Level 1 Summer 2008



Alexandria Student Branch 86


The following example shows a function that is used to add 2 input numbers.

Function [op]=summation(ip1,ip2)
op=ip1+ip2;
%------------------------------------------------------------------------------------

Very important to note is that this M-File must be saved with the same function name.
In the previous example, it must be saved with the name summation.m.
Running a function M-File is refered to as calling the function. A function is called
with its input arguments and output arguments. For example:

>>x=summation(19,5)
This command will assign 19 to ip1, 5 to ip2 calculates op and assign it to x.

One thing to notice is that the variables op, ip1, ip2 are internal variables in the
function summation, and they are not affected by and do not affect the terminal
behavior as seen from outside. You must respect the variables declared in the
declaration line inside the function itself when you are programming it. However, when
you call the function from outside, you can use whatever variables you want. No
confusion will result from changing or mixing the variables used in calling the function.
The only rule seen from outside will be the order of the inputs.

You can call functions inside the code of a certain function. Also, you can define
more than one function in the same M-file, but this procedure is a bit advanced and
you will never find yourself forced to use it.

- Note:
To add some information about the function, you can enter them in the form of
comments just after the function declaration.

Example:
Function [op]=summation(ip1,ip2)
%This function is use to add to numbers.
op=ip1+ip2;

Now try in the command window to type help summation and the written comments
will appear.


Matlab Level 1 Summer 2008



Alexandria Student Branch 87

Debugging M-Files

When you write complex programs, errors will always appear depending on your
experience. In complex programs where functions prepare variables or values used by
other functions, or where program flow is shared among different segments of the
program, the process of diagnosing an error (recognizing its cause) might be very
tricky. The error might be a syntax error. In this case, you might need to read through
all of the different segments of your program searching for that missing comma, or
searching for that instruction where you opened 8 brackets but only closed 7. In fact,
these syntax errors are the easiest to diagnose and correct. Actually Matlab wont let
you need to read through the whole program, because it will issue an error report
containing the line number of the miswritten instruction as soon as a syntax error is
encountered.

The frightening type of errors is not syntax errors, but logical errors. Logical
errors are errors in which instructions are written correctly from the syntax point of
view, but fail to achieve the task you intended because you didnt program them
correctly. The problem with logical errors is that Matlab may not necessarily be able to
recognize the error. In most of the cases, a single logical error may have an effect
which propagates with the running of the program, thus causing some subsequent
functions to operate on incorrect values and produce other incorrect values. We might
reach a stage where the values are so ruined that matlab encounters a problem in
execution. At this point, Matlab will issue a runtime error report describing the problem
it just encountered. This might trick you into thinking that this instruction is erroneous
even though it is not. The instruction may be correct, but operating on invalid values
whose invalidity is caused by an indetectable logical error in an earlier portion of the
program. In some cases, the logical errors might cause absolutely no execution
problems or runtime errors. In this case, the errors will propagate in a totally
indetectable manner, causing execusion of the program to end properly. However, you
as a programmer, will recognize that the final result is incorrect.

Diagnosing logical errors is a much harder task than diagnosing syntax errors,
because Matlab will not recognize the error in most cases. We need to depend on
ourselves in tracing the program execution in order to know what is going wrong. But
we cant do so if the program runs continuously. We need to run the program step-by-
step. Also, we need some diagnostic tools that give us the ability to check our variables
before and after the execution of every instruction in order to judge on the validity of
that instruction. This is what debugging offers.
What is debugging?
It is a mode of program execution in which a program runs stepo-by-step, giving
us the chance to inspect the values of the variables and the flow of control in order to
detect and remove logical errors (bugs).
Matlab Level 1 Summer 2008



Alexandria Student Branch 88

Debugging is done by placing breakpoints next to the instructions at which we
want execution to halt. Matlab lets you add and remove breakpooints as you like.
When stopped at a breakpoint, you can hover with the mouse over any variable
created previously. Matlab will show you the contents of that variable.

Additionally, Matlab gives you the ability to use the comand prompt in debug
mode. The prompt indicator will take the following form (k>>) instead of (>>). The
variables used by the current function are also listed in the workspace browser so that
you can query or modify these variables.

We can use the command prompt as if we were not in debug mode to try out an
instruction, test its operation and trying alternative forms. We can then continue
debugging whenever we want.















Matlab Level 1 Summer 2008



Alexandria Student Branch 89

Additional Information:
Understanding the Matlab Path Search

When Matlab needs any external file, such as an image file, a sound file or an
excel file, or any user file such as a gui figure file or an M-File, it searches in a set of
folders which we call the path. Thus, any external file or user file we want to use with
Matlab must exist in the path. This means that the folder in which it resides must be
on the path.
We can either place the files in one of the folders already on the path, or we can
add or remove folders from the path definitions by going to File -> Set Path in the
Matlab main window.
Two of the most common folders that exist in the path for Matlab users are the
work folder residing in the Matlab directory, and the arbitrary folder chosen by the
user in the current directory window on the main window.
Any M-File you save is automatically saved in the current directory. The current
directory is work by default, unless you choose an alternative folder.
If a file is on your computer on hard or floppy disk, Matlab might not be able to
find the file if its path isnt defined. Thus, you will need in this case to either copy the
file into one of the folders on the path, or to add the files directory to the Matlab path
definition.

Types of Variables

A Matlab variable is essentially a tag that you assign to a value while that value
remains in memory. The tag gives you a way to reference the value in memory so that
your programs can read it, operate on it with other data, and save it back to memory.
Types of Variables
MATLAB provides three basic types of variables:
- Local Variables
- Global Variables
- Persistent Variables

Local Variables

Each MATLAB function has its own local variables. These are separate from those of
other functions and from those of the base workspace. Variables defined in a function
do not remain in memory from one function call to the next, unless they are defined as
global or persistent. Scripts, on the other hand, do not have a separate workspace.
They store their variables in a workspace that is shared with the caller of the script.
Matlab Level 1 Summer 2008



Alexandria Student Branch 90

When called from the command line, they share the base workspace. When called from
a function, they share that function's workspace. Note: If you run a script that alters a
variable that already exists in the caller's workspace, that variable is overwritten by
the script.

Global Variables

If you want more than one function to share a single copy of a variable, simply declare
the variable 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. Although it is not required, using
capital letters for the names of global variables helps distinguish them from other
variables. For example, create an M-file called falling.m.

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

Persistent Variables

Characteristics of persistent variables are:
- you can declare and use them within M-file functions only.
- Only the function in which the variables are declared is allowed access to it.
- MATLAB does not clear them from memory when the function exits, so their
value is retained from one function call to the next.
You must declare persistent variables before you can use them in a function. It is
usually best to put your persistent declarations toward the beginning of the function.
You would declare persistent variable SUM_X as follows:

persistent SUM_X

If you clear a function that defines a persistent variable (i.e., using clear functionname
or clear all), or if you edit the M-file for that function, MATLAB clears all persistent
variables used in that function.

Guidelines to Using Variables

The same guidelines that apply to MATLAB variables at the command line also apply to
variables in M-files:
- You do not need to type or declare variables used in M-files (with the possible
exception of designating them as global or persistent).
Matlab Level 1 Summer 2008



Alexandria Student Branch 91

- Before assigning one variable to another, you must be sure that the variable on
the right-hand side of the assignment has a value.
- Any operation that assigns a value to a variable creates the variable, if needed,
or overwrites its current value, if it already exists.

Keywords

MATLAB reserves certain words for its own use as keywords of the language. To list the
keywords, type >>iskeyword
ans =
'break'
'case'
'catch'
'continue'
'else'
'elseif'
'end'
'for'
'function'
'global'
'if'
'otherwise'
'persistent'
'return'
'switch'
'try'
'while'

You should not use MATLAB keywords other than for their intended purpose. For
example, a keyword should not be used as follows:

while = 5;
??? while = 5;
|
Error: Expected a variable, function, or constant, found "=".




Matlab Level 1 Summer 2008



Alexandria Student Branch 92

Storage Types in Matlab

Many storage types in Matlab are provided to serve the different natures of
applications and the storage and precision requirements of each. We will discuss here
some of the common types.

Double
This data type uses most storage capacity ( 8 bytes per scalar), but provides the
highest precision. You can define a double number to any number of decimal places,
and carry out any type of mathematical operation on this number.

UINT8
This data type uses only 8 bits to store the number, but it can only store integer
numbers from 0 to 255. This type is useful for RGB (24-bits) image storage. The only
operations you can do on UINT8 variables are simple integer operations such as
integer addition or multiplication.

UINT16
This data type is similar to UINT8,except that is uses 16 bits instead of 8 to represent
the integer. Hence, you can define integers from 0 up to 65,535.

Char (Strings)
The data type char is used to store strings. If you define a variable type as char, then
you write and read the characters while the ASCII conversions are done automatically.
Strings are arrays of characters. All rules of arrays apply to strings. To enter a
character array, you must enclose it in single quotes not in square brackets like arrays
of double or arrays of UINT.
Example:
A=This string is 34 characters long. If you write this string in Matlab, you will find that
A is a 1-by-34 array of type char.

Structures
Structures are stored in a storage type called structure.

Cell Arrays
Cell arrays are stored in storage type called Cell Array.






Matlab Level 1 Summer 2008



Alexandria Student Branch 93

Data type conversions

Conversion To Double
You can convert any variable from any numeric data type to double using the function
double. If B is a UINT16 variable, then B=double(B) will cause Bs data type to
change from UINT16 to double.

Conversion to UINT8
You can convert any pure numeric variable from any data type to UINT8 using the
function UINT8. When you are converting from double to UINT8, there are two main
considerations to keep in mind:

Any decimals will be discarded because UINT8 is an integer data type. This loss
of information is irreversible.
Any numbers less than 0 will saturate to 0 and any numbers greater than 255
will saturate to 255 upon conversion. This saturation is irreversible.

Conversion to UINT16
You can convert any pure numeric variable from any data type to UINT16 using the
function UINT16. When you are converting from double to UINT16, there are two
main considerations to keep in mind:

Any decimals will be discarded because UINT8 is an integer data type. This loss
of information is irreversible.
Any numbers less than 0 will saturate to 0 and any numbers greater than 65,535
will saturate to 65,535 upon conversion. This saturation is irreversible.

Conversion To Char
You can convert any pure numeric variable from any data type to char using the
function char. This function returns the character or string of characters whose
ASCII values are given by the numeric array input to the function. If the numberis not
an ASCII integer, it is floored and saturated until it matches the ASCII values.

Conversions Between Structures And Cell Arrays
You can convert a structure to a cell array and vice versa. You can convert an M-by-N
structure with P fields to an M-by-N-by-P cell array using the function struct2cell. You
can convert an M-by-N-by-P cell array to an M-by-N structure with P fields using the
function cell2struct and the function fieldnames to specify the names of the fields.



Matlab Level 1 Summer 2008



Alexandria Student Branch 94

Sting processing

Entering Strings
You can enter a string simply as:
>>A=string. This creates a 1-by-6 array of characters and stores it in A.

ASCII Conversions (char <-> double)
You can convert a char variable to double using the functiondouble.
>>A=double (A) will return a 1-by-6 array of type double containing the ASCII code of
the letters. You can convert an array of ASCII values to a string using the function
char.
>>char (48) returns the character whose ASCII code is 48.

String Comparison (strcmp)
Suppose that we want to compare two strings. If one of the strings is stored in A and
the second in B,then the relational test A==B will carry out an element-by-element
(letter-by-letter) comparison. If the sizes of A and B are not the same, this operational
expression will return an error.we have a special function that compares strings to test
whether or not they are identical.This functionis strcmp.

Strcmp(A,B) returns 1 if A and B are identical strings and returns 0
otherwise.

Numbers In String Format
We will often meet the case where a string contains a number such as A=56.8. This
number is not usable as a number because it is in string format. We might not be as
interestedin knowing the ASCII codes of the numeric symbols and the decimal point as
we might be in changing this written number to a numeric format that may be used as
a number . We have two functions that read numbers from strings and write numbers
to strings format.
B=str2num(56.8) returns the numeric value 56.8 in B.
B=num2str(47.8) returns the string 47.8, in B.


Two-Dimensional String Character Arrays
Sometimes we get to meet an M-by-N array of characters. Each row of such an array is
a string. So we have M stings, each of which is N characters long. We may write M
Strings into an array but we must make sure that the number of characters is the
same for all strings. If not, we must pad the short strings with blank spaces.


Matlab Level 1 Summer 2008



Alexandria Student Branch 95


Indexing Into Strings
We may index into strings just as we index into any other type arrays. If A is a 10-
character string, then A(6:end) will return the last 5 characters of string A.

String Concatenation
We can concatenate strings just as we can concatenate any other type of arrays. If A is
a string that holds The temperature today is and B is a string that holds
Centigrades. And T is a variable that holds the number 34.2, then the instruction
C=[A num2str (T) B] will return the following string in C:
The temperature today is 34.2 Centigrades.

String Evaluation (eval)
The function eval accepts a string input argument, and causes the content of this
string to evaluate just as if it was written in the command prompt.
As an example, assume that A=45,B=+ and C=35,then the instruction

eval([sum=A+B+C;])

Will cause the variable sum to be equal to 80. Matlab starts by evaluating the input
argument to eval. The input argument in this case evaluates to the string
Sum=45+35; . Then, Matlab will evaluate this expression as if it was written in the
command prompt.

Some Other Useful String Functions

blanks deblank ischar Isletter strvcat
strncmp strcmpi strnmpi Findstr Strjust
strmatch strrep strtok Upper Lower
int2str mat2str sprintf Sscanf







Matlab Level 1 Summer 2008



Alexandria Student Branch 96

Session 5 Tasks
Task 1:
Write a Matlab function to draw the curves of sin(2nft) where f is the
frequency, t is the time range over which this function is drawn and n is a number
between 1 & 4 indicating the number of curves to be drawn using subplot command.
The name of this function is task1_sin. It has 4 inputs: start of t, end of t, f and n.

Task 2:
Write a Matlab function to draw the curves of sin(2ft), cos(2ft), tan(2ft)
where f is the frequency, t is the time range over which this functions are drawn .
The name of this function is task2_trig. It has 4 inputs: start of t, end of t, f and n,
where n is a number between 1 & 4.
If n=1, then sin(2ft) is drawn against t.
If n=2, then cos(2ft) is drawn against t.
If n=3, then tan(2ft) is drawn against t.
If n=4, then the functions is drawn against t in the same figure, each with different
color and line style and marker.
The function must insert a title for every curve and a legend box in case n=4.

Task 3:
It is required to create a simple dialing interface using a single Matlab function.
The user must enter a number and a dialing scheme, either P for pulse or T for soft
touch tone. The program must then produce the desired dialing signal over the analog
interface (sound card). This interface may be coupled actually to the telephone line and
the program may be used as an actual dialing mechanism. The dialing signal is
described as follows.

Soft Touch Tone (DTMF) Dialing

The following diagram illustrates the dialing pad. Note that every button has a
row number and a column number. The different rows and columns are assigned
different frequencies (Dual Tone Multiple Frequency or DTMF dialing). When you touch
a button, the telephone set produces a sound signal which is the sum of two sinusoidal
waves having the row and column frequencies, for as long as the button is touched.
For example, when you touch 4, the two frequencies are 770Hz and 1209Hz.





Matlab Level 1 Summer 2008



Alexandria Student Branch 97















The bottom left key has a symbol called an asterisk (*) and is called the star key.
The bottom right key has a symbol called the octothorpe (#) and is called the pound
key, cross-hatch key or the number key.
It is required from the program to emulate a 0.2 seconds touch of the buttons
with time separations of 1/12 seconds between successive touches. The sound
sampling rate must be 44100sps and the amplitude must be 0.3 for all sine waves.

Pulse Dialing

In pulse dialing, impulsive ticks are generated at the telephone set. The number
of pulses corresponding to any button is determined as follows:

Button
Number of
Pulses
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
0 10
* None
# None

1 2 3
4 5 6
7 8 9
* 0 #
697Hz
770Hz
852Hz
941Hz
1209Hz 1336Hz 1477Hz
Matlab Level 1 Summer 2008



Alexandria Student Branch 98

The program is required to produce the pulses at a rate of 5 pulses per second
for any button pressed, with a separation of 0.8 seconds between successive buttons.
Note that a single pulse may be generated by playing the vector [zeros(1,10)
ones(1,80) zeros(1,10)] at 44100sps.


Task 4: Image Ciphering & Deciphering functions:

It is required to write 2 Matlab functions. The first one is used to cipher a certain
image. Image Ciphering means to completely hide the picture details or completely
change the picture so it can be send securely over communication system such as the
mobile systems and the Internet. You can use this function to send pictures to your
friends securely.
The second function is the opposite. It is used to reobtain the original image from the
hidden or uncleared image which is called Image Deciphering.
These functions must be used for any image with any dimensions and details.



























Matlab Level 1 Summer 2008



Alexandria Student Branch 99

Session 6

Content
Part 1: Matlab Graphical Objects
Handle Graphic Objects
Handle Graphic Object Properties
Obtaining Handles
Querying Handle Graphic Object Properties
Modifying Handle Graphic Object Properties
Part 2: Matlab GUI
What is a GUI?
Steps of Making GUIs
Debugging & Running GUIs
GUI Example 1: A Simple GUI that Adds 2 Numbers
Additional Information
Tasks.


Part 1: Matlab Graphical Objects

Handle Graphic Objects
A graphical object in Matlab may be a figure or any of its components. Look at
the following figure. The main figure window is a graphical object. The axes make a
graphical object. The plotted curve is a graphical object. The text box containing the
figures title Signal Preview Window is a graphical object. All text boxes containing
texts are graphical objects. The choice menu containing the list of signals, the slider for
volume control, the edit box for sampling rate entry and the preview pushbutton are
also graphical objects.

In Matlab, every graphical object has a set of properties that provides this object
with full functionality and provides the user with full control over that objects
behavior. Every property has a certain value. The user has the ability to query and
modify any objects properties, i.e. to read and write the properties values.

Matlab Level 1 Summer 2008



Alexandria Student Branch 100

In addition to properties, some objects have callback functions. These are
functions that are executed whenever the user interacts with the objects. An example
of an object whose callback function is of remarkable importance is the pushbutton.



It is obvious that we will be dealing in the next stage with multiple objects. In
our dealing with graphical objects, we will depend on querying and modifying
properties as well as programming callback functions for an ensemble of graphical
objects brought together to assemble something like the figure shown above. The
programming wont be easy except if every object has an ID with which we may call
that object from among the others. In fact, each object has an Identification Number
called a handle. The identification is called a handle because once we have grip of it,
we have full control of the object. Every graphical object created by Matlab is assigned
a handle. This is why graphical objects in Matlab are also called handle graphic objects.

There are many types of handle graphic objects. Efficient design of graphical
items in Matlab requires good understanding of handle graphical objects and their
Matlab Level 1 Summer 2008



Alexandria Student Branch 101

properties. In the rest of this section, we will demonstrate the different types of handle
graphic objects. In the next section we will inspect their different properties.

The Root
The root refers to the main computer display screen. There is only one root. The
root can never be created nor destroyed. It exists as it is. The handle of the root is
always 0.
Figures
A figure is a window that appears on the root to accommodate some other
objects. You can create or destroy (close) figures. You can open multiple figures at the
same time. Figures are said to be children of the root. The root is said to be the parent
of all objects. All the objects inside a figure are said to be children of that figure. That
figure is said to be the parent of its children. When a parent is destroyed, all of its
children are destroyed. Figure handles are always integers starting from 1.
Axes
Axes are plot boxes that accommodate plots or images. Axes are children of
figures. Axes are parents of their children objects. Axes children include the X axis, the
Y axis, the lines or surfaces or images plotted, any legend, label textetc.
Static Text Boxes
A static text box is a UI control box that accommodates text to be displayed on
the figure window without user interaction with it. For an example, review the title
Signal Preview Window or the caption Sample Rate: in the previous figure.
Edit Boxes
An edit box is an input box UI control that interacts with the user. It allows the
user to type in it a string. In the figure above, the sample rate is typed by the user in
an edit box.
List Boxes
A list box is a UI control that lists several options for a user to choose from. We
are then able of knowing what the user had chosen.
Popup Menus
A popup menu is a UI control similar in purpose to a list box. A menus pops up
when the user clicks on this control. When the user makes a selection from the menu,
the menu is retracted and the field shows the user choice only.


Matlab Level 1 Summer 2008



Alexandria Student Branch 102

Radio Buttons
A radio button is a UI control usually used as a member of an ensemble of radio
buttons, from which the user may select only one.
Checkbox
A checkbox is a UI control that the user either checks or unchecks. It may be
used to provide the user with a yes or no decision option.
Pushbuttons
A pushbutton is a UI control that executes a callback function when pressed.
Toggle Buttons
A toggle button looks similar to a pushbutton but it toggles its state
(pressed/unpressed) at every click.
Sliders
A slider is a UI control that provides the user with a graphical means of
configuring a certain value over a certain range by graphical motion of a slider using
the mouse.
Frames
Frames are UI controls that are used to visually group related objects together
by including them within borders. They have almost no significance from the
programming point of view.


















Matlab Level 1 Summer 2008



Alexandria Student Branch 103

Handle Graphic Object Properties
Each type of handle graphic objects has a set of properties. Every property
governs some behavioral aspects of the object someway. However, some properties
are more important than others. As there are too many properties than one could keep
in mind, we will discuss the most significant properties for each type of handle graphic
objects we mentioned in the previous section.

The Root
The following properties are related to the root. Note that root properties are can
be queried but not modified by Matlab. You can read the screen resolution from within
Matlab, but you cant change it.
o Units
A property that determines the units in which positions and lengths are to be
measured. The possible values are:
[inches, centimeters, points, pixels, characters, normalized].
Normalized Units: Screen Width=1, Screen Height=1. (Aspect ratio ~=1).
Pixel Units: Screen Width and Height in pixels varies according to system settings.
o ScreenSize

This is a 1-by-4 vector whose elements are as follows:
[ X of bottom-left-most pixel Y of bottom-left-most pixel Width Length].
These four elements are expressed in terms of the chosen units. For example, If your
resolution setting is 800x600 and you choose pixel units, the screen size vector would
be [1 1 800 600]. If the chosen units are normalized, the screen size vector would be
[0 0 1 1].
o PointerLocation
Position of the mouse pointer on the screen expressed in terms of the chosen units.
o ScreenDepth
The color depth configuration of the system. Possible values are 4 for 16 colors,
8 for 256 colors, 16 for 16-bit color or 24 for 24-bit color.
o Children
Handles of all children (graphical objects) falling under the root.
o Type
This property always has the value root for the root.
Matlab Level 1 Summer 2008



Alexandria Student Branch 104

Figures
o Color
This is a 1-by-3 vector of RGB intensities defining the figure color. The intensities
range from 0 to 1.
o Colormap
An array of data defining an image to be used as a background for the figure.
o Pointer
The pointer shape to be used when the mouse pointer hovers over the figure.
Possible values are [ crosshair | fullcrosshair | arrow | ibeam | watch | topl | topr | botl
| botr | left | top | right | bottom | circle | cross | fleur | custom ].
o PointerShapeCData
For a custom pointer, this 16-by-16 array contains the image for the custom
pointer to use.
o Units
A property that determines the units in which positions and lengths are to be
measured. The possible values are:
[inches | centimeters | points | pixels | characters | normalized].
Normalized Units: Screen Width=1, Screen Height=1. (Aspect ratio ~=1).
Pixel Units: Screen Width and Height in pixels varies according to system settings.
o Position
This is a 1-by-4 vector whose elements are as follows:
[X of bottom-left corner Y of bottom-left corner Width Length].
These four elements are expressed in terms of the chosen units.
o Tag
A characteristic name you choose to distinguish this object from all other objects.
o Name
The string that appears in the window bar and in the taskbar under windows.
o Resize
A property that defines whether the figure is or is not resizable by the user. This
property may take one of two values, either On or Off.
o Type
This property has always the value figure for figures.
Matlab Level 1 Summer 2008



Alexandria Student Branch 105

Axes
o Units
A property that determines the units in which positions and lengths are to be
measured. The possible values are:
[inches, centimeters, points, pixels, characters, normalized].
Normalized Units: Screen Width=1, Screen Height=1. (Aspect ratio ~=1).
Pixel Units: Screen Width and Height in pixels varies according to system settings.
o Position
This is a 1-by-4 vector whose elements are as follows:
[X of bottom-left corner Y of bottom-left corner Width Length].
These four elements are expressed in terms of the chosen units.
o DataAspectRatio
This is a 1-by-3 vector that determines the aspect ratio of plotting data. An
aspect ratio [1 1 1] keeps x-, y- and z-axis scales all the same. An aspect ratio of [1
0.5 1] makes the scale of the y-axis half of that of the x- and z-axis.
o PlotBoxAspectRatio
This is a 1-by-3 vector that determines the aspect ratio of the plotbox in which
the plot is positioned. An aspect ratio of [1 1 1] makes the plot box a cube. Any
different aspect ratio results in a cuboidal plotbox.
o NextPlot
This property controls how the axes will behave whenever a new plot command
is issued. Will the axes add the new plot to the existing one, replace the existing one
while keeping its configuration unchanged, or will it refresh completely as if it was
deleted and recreated by the new plot?
This property may take one of three values. These are [add | replace |
replacechildren]. The first value causes the axes to simply add the new plot to the
existing ones and keep axes configuration unchanged. The second value causes the
whole axes to be replaced by new ones accommodating the new plot. The third value
makes the axes delete the old plot and create the new one, while keeping all axes
configuration unchanged.


o View
This is a 1-by-2 vector of degree angles defining the angles of azimuth and elevation of
the three-dimensional look direction at the axes. This property is especially useful for
rotating 3-D plots.
Matlab Level 1 Summer 2008



Alexandria Student Branch 106

o Title
This property has a string value that displays as a title for the plot. The title is a
child of the axes.
o XGrid
This property determines whether or not the x-grid is made visible. It has two
values: On and Off.
o XLim
This is a 1-by-2 vector defining the limits of the x-axis. It takes the form [xmin
xmax].
o XTick
This property defines the positions at which x-axis ticks are positioned. For
image display, set this propertys value to [].
o XTickLabel
This property defines the labels written under the x-ticks. For image display set
this propertys value to [].
o YGrid
This property determines whether or not the y-grid is made visible. It has two
values: On and Off.
o YLim
This is a 1-by-2 vector defining the limits of the y-axis. It takes the form [ymin
ymax].
o YTick
This property defines the positions at which y-axis ticks are positioned. For
image display, set this propertys value to [].
o YtickLabel
This property defines the labels written under the y-ticks. For image display set
this propertys value to [].
o Z-Grid
This property determines whether or not the z-grid is made visible. It has two
values: On and Off.
o ZLim
Matlab Level 1 Summer 2008



Alexandria Student Branch 107

This is a 1-by-2 vector defining the limits of the z-axis. It takes the form [zmin
zmax].
o ZTick
This property defines the positions at which z-axis ticks are positioned.
o ZTickLabel
This property defines the labels written under the z-ticks.
o XScale
This property defines whether the x-axis is linearly or logarithmically scaled. The
possible values are linear and log.
o YScale
This property defines whether the y-axis is linearly or logarithmically scaled. The
possible values are linear and log.
o ZScale
This property defines whether the z-axis is linearly or logarithmically scaled. The
possible values are linear and log.
o Tag
A characteristic name you choose to distinguish this object from all other objects.
o Children
This propertys value is the set of all handles of the axes children.
o Type
This property is always axes for axes.


Text Boxes
o Units
A property that determines the units in which positions and lengths are to be
measured. The possible values are:
[inches, centimeters, points, pixels, characters, normalized].
Normalized Units: Screen Width=1, Screen Height=1. (Aspect ratio ~=1).
Pixel Units: Screen Width and Height in pixels varies according to system settings.
o Position
This is a 1-by-4 vector whose elements are as follows:
Matlab Level 1 Summer 2008



Alexandria Student Branch 108

[X of bottom-left corner Y of bottom-left corner Width Length].
These four elements are expressed in terms of the chosen units.
o String
This propertys value is the text string to be written inside the text box.
o BackgroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the text box background.
o ForegroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the text appearing in the object.
o FontName
The font to be used for the text. Possible values are times, arial, courieretc.
o FontSize
A scalar defining the size of the font used for the objects text.
o FontWeight
This property has four values: [light | normal | demi | bold]. It determines how
thick the font is.
o Visible
This property determines the visibility of the object. It has two possible values: [
On | Off ].
o Tag
A characteristic name you choose to distinguish this object from all other objects.
o ToolTipString
A help string in a yellow patch that appears whenever the user hovers with the
mouse pointer over the object in order to give him/her a tip about the item or how to
use it.
o HorizontalAlignment
This property defines whether the objects text is aligned right, centered or left.
It has three possible values: [left | centered | right].




Matlab Level 1 Summer 2008



Alexandria Student Branch 109



Edit Boxes

o Units
A property that determines the units in which positions and lengths are to be
measured. The possible values are:
[inches, centimeters, points, pixels, characters, normalized].
Normalized Units: Screen Width=1, Screen Height=1. (Aspect ratio ~=1).
Pixel Units: Screen Width and Height in pixels varies according to system settings.
o Position
This is a 1-by-4 vector whose elements are as follows:
[X of bottom-left corner Y of bottom-left corner Width Length].
These four elements are expressed in terms of the chosen units.
o String
This propertys values holds a string to be displayed in the edit box or a string
entered by the user in the edit box.
o BackgroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the edit box background.
o ForegroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the text appearing in the object.

o FontName
The font to be used for the text. Possible values are times, arial, courieretc.
o FontSize
A scalar defining the size of the font used for the objects text.
o FontWeight
This property has four values: [light | normal | demi | bold]. It determines how
thick the font is.
o Visible
Matlab Level 1 Summer 2008



Alexandria Student Branch 110

This property determines the visibility of the object. It has two possible values: [
On | Off ].
o Enable
This property determines whether the object is active (allows user interaction) or
inactive (doesnt allow user interaction). It has two possible values: [ On | Off].
o Tag
A characteristic name you choose to distinguish this object from all other objects.
o ToolTipString
A help string in a yellow patch that appears whenever the user hovers with the
mouse pointer over the object in order to give him/her a tip about the item or how to
use it.
o HorizontalAlignment
This property defines whether the objects text is aligned right, centered or left.
It has three possible values: [left | centered | right].


Pushbuttons

o Units
A property that determines the units in which positions and lengths are to be
measured. The possible values are:
[inches, centimeters, points, pixels, characters, normalized].
Normalized Units: Screen Width=1, Screen Height=1. (Aspect ratio ~=1).
Pixel Units: Screen Width and Height in pixels varies according to system settings.
o Position
This is a 1-by-4 vector whose elements are as follows:
[X of bottom-left corner Y of bottom-left corner Width Length].
These four elements are expressed in terms of the chosen units.
o String
This propertys value contains the string to be displayed in the pushbutton.
o BackgroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the pushbutton.
Matlab Level 1 Summer 2008



Alexandria Student Branch 111



o ForegroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the text appearing in the object.
o FontName
The font to be used for the text. Possible values are times, arial, courieretc.
o FontSize
A scalar defining the size of the font used for the objects text.
o FontWeight
This property has four values: [light | normal | demi | bold]. It determines how
thick the font is.
o Visible
This property determines the visibility of the object. It has two possible values: [
On | Off ].
o Enable
This property determines whether the object is active (allows user interaction) or
inactive (doesnt allow user interaction). It has two possible values: [ On | Off].
o Tag
A characteristic name you choose to distinguish this object from all other objects.
o ToolTipString
A help string in a yellow patch that appears whenever the user hovers with the
mouse pointer over the object in order to give him/her a tip about the item or how to
use it.
o HorizontalAlignment
This property defines whether the objects text is aligned right, centered or left.
It has three possible values: [left | centered | right].


Toggle Buttons

o Units
Matlab Level 1 Summer 2008



Alexandria Student Branch 112

A property that determines the units in which positions and lengths are to be
measured. The possible values are:
[inches, centimeters, points, pixels, characters, normalized].
Normalized Units: Screen Width=1, Screen Height=1. (Aspect ratio ~=1).
Pixel Units: Screen Width and Height in pixels varies according to system settings.
o Position
This is a 1-by-4 vector whose elements are as follows:
[X of bottom-left corner Y of bottom-left corner Width Length].
These four elements are expressed in terms of the chosen units.
o String
This propertys value contains the string to be displayed in the toggle button.
o BackgroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the toggle button.
o ForegroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the text appearing in the object.
o FontName
The font to be used for the text. Possible values are times, arial, courieretc.
o FontSize
A scalar defining the size of the font used for the objects text.
o FontWeight
This property has four values: [light | normal | demi | bold]. It determines how
thick the font is.
o Visible
This property determines the visibility of the object. It has two possible values: [
On | Off ].
o Enable
This property determines whether the object is active (allows user interaction) or
inactive (doesnt allow user interaction). It has two possible values: [ On | Off].
o Value
Matlab Level 1 Summer 2008



Alexandria Student Branch 113

This propertys value holds the toggle state of the button. A value of 0 indicates
an unpressed button or unpressing the button. A value of 1 indicates a pressed button
or pressing the button.
o Tag
A characteristic name you choose to distinguish this object from all other objects.
o ToolTipString
A help string in a yellow patch that appears whenever the user hovers with the
mouse pointer over the object in order to give him/her a tip about the item or how to
use it.
o HorizontalAlignment
This property defines whether the objects text is aligned right, centered or left.
It has three possible values: [left | centered | right].


Radio Buttons

o Units
A property that determines the units in which positions and lengths are to be
measured. The possible values are:
[inches, centimeters, points, pixels, characters, normalized].
Normalized Units: Screen Width=1, Screen Height=1. (Aspect ratio ~=1).
Pixel Units: Screen Width and Height in pixels varies according to system settings.
o Position
This is a 1-by-4 vector whose elements are as follows:
[X of bottom-left corner Y of bottom-left corner Width Length].
These four elements are expressed in terms of the chosen units.
o String
This propertys value contains the string to be displayed in the radio buttons
field.
o BackgroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the radio button field background.
o ForegroundColor
Matlab Level 1 Summer 2008



Alexandria Student Branch 114

This property is a 1-by-3 vector that defines the RGB intensities of the color of
the text appearing in the object.

o FontName
The font to be used for the text. Possible values are times, arial, courieretc.
o FontSize
A scalar defining the size of the font used for the objects text.
o FontWeight
This property has four values: [light | normal | demi | bold]. It determines how
thick the font is.
o Visible
This property determines the visibility of the object. It has two possible values: [
On | Off ].
o Enable
This property determines whether the object is active (allows user interaction) or
inactive (doesnt allow user interaction). It has two possible values: [ On | Off].
o Value
This propertys value holds the state of the radio button. A value of 0 indicates a
deselected button or deselecting the button. A value of 1 indicates a selected button or
selecting the button.
o Tag
A characteristic name you choose to distinguish this object from all other objects.
o ToolTipString
A help string in a yellow patch that appears whenever the user hovers with the
mouse pointer over the object in order to give him/her a tip about the item or how to
use it.
o HorizontalAlignment
This property defines whether the objects text is aligned right, centered or left.
It has three possible values: [left | centered | right].


Checkboxes
Matlab Level 1 Summer 2008



Alexandria Student Branch 115


o Units
A property that determines the units in which positions and lengths are to be
measured. The possible values are:
[inches, centimeters, points, pixels, characters, normalized].
Normalized Units: Screen Width=1, Screen Height=1. (Aspect ratio ~=1).
Pixel Units: Screen Width and Height in pixels varies according to system settings.
o Position
This is a 1-by-4 vector whose elements are as follows:
[X of bottom-left corner Y of bottom-left corner Width Length].
These four elements are expressed in terms of the chosen units.
o String
This propertys value contains the string to be written next to the checkbox.
o BackgroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the checkbox field background.
o ForegroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the text appearing in the object.
o FontName
The font to be used for the text. Possible values are times, arial, courieretc.
o FontSize
A scalar defining the size of the font used for the objects text.
o FontWeight
This property has four values: [light | normal | demi | bold]. It determines how
thick the font is.
o Visible
This property determines the visibility of the object. It has two possible values: [
On | Off ].
o Enable
This property determines whether the object is active (allows user interaction) or
inactive (doesnt allow user interaction). It has two possible values: [ On | Off].

Matlab Level 1 Summer 2008



Alexandria Student Branch 116



o Value
This propertys value holds the check state of the checkbox. A value of 0
indicates an unchecked box or unchecking the box. A value of 1 indictaes a checked
box or checking the box.
o Tag
A characteristic name you choose to distinguish this object from all other objects.
o ToolTipString
A help string in a yellow patch that appears whenever the user hovers with the
mouse pointer over the object in order to give him/her a tip about the item or how to
use it.
o HorizontalAlignment
This property defines whether the objects text is aligned right, centered or left.
It has three possible values: [left | centered | right].


Sliders

o Min
This property is a scalar that defines the value corresponding to the lower bound
of the slider value range.
o Max
This property is a scalar that defines the value corresponding to the upper bound
of the slider value range.
o Value
This property is a scalar corresponding to the position of the slider in its range.
o Units
A property that determines the units in which positions and lengths are to be
measured. The possible values are:
[inches, centimeters, points, pixels, characters, normalized].
Normalized Units: Screen Width=1, Screen Height=1. (Aspect ratio ~=1).
Pixel Units: Screen Width and Height in pixels varies according to system settings.
Matlab Level 1 Summer 2008



Alexandria Student Branch 117

o Position
This is a 1-by-4 vector whose elements are as follows:
[X of bottom-left corner Y of bottom-left corner Width Length].
These four elements are expressed in terms of the chosen units.
o Tag
A characteristic name you choose to distinguish this object from all other objects.
o ToolTipString
A help string in a yellow patch that appears whenever the user hovers with the
mouse pointer over the object in order to give him/her a tip about the item or how to
use it.


Listboxes

o Units
A property that determines the units in which positions and lengths are to be
measured. The possible values are:
[inches, centimeters, points, pixels, characters, normalized].
Normalized Units: Screen Width=1, Screen Height=1. (Aspect ratio ~=1).
Pixel Units: Screen Width and Height in pixels varies according to system settings.
o Position
This is a 1-by-4 vector whose elements are as follows:
[X of bottom-left corner Y of bottom-left corner Width Length].
These four elements are expressed in terms of the chosen units.
o String
This propertys value is a cell array of strings, each of which will be written on a
separate line in the list and will be considered as an individual choice.
o BackgroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the list box background.
o ForegroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the text appearing in the object.
Matlab Level 1 Summer 2008



Alexandria Student Branch 118

o FontName
The font to be used for the text. Possible values are times, arial, courieretc.
o FontSize
A scalar defining the size of the font used for the objects text.
o FontWeight
This property has four values: [light | normal | demi | bold]. It determines how
thick the font is.
o Visible
This property determines the visibility of the object. It has two possible values: [
On | Off ].
o Enable
This property determines whether the object is active (allows user interaction) or
inactive (doesnt allow user interaction). It has two possible values: [ On | Off].
o Value
This propertys value holds the number of the selected line in the listbox.
Possible values are integers ranging from 1 to the number of strings in its cell array.
o Tag
A characteristic name you choose to distinguish this object from all other objects.
o ToolTipString
A help string in a yellow patch that appears whenever the user hovers with the
mouse pointer over the object in order to give him/her a tip about the item or how to
use it.

Popup Menus

o Units
A property that determines the units in which positions and lengths are to be
measured. The possible values are:
[inches, centimeters, points, pixels, characters, normalized].
Normalized Units: Screen Width=1, Screen Height=1. (Aspect ratio ~=1).
Pixel Units: Screen Width and Height in pixels varies according to system settings.
o Position
Matlab Level 1 Summer 2008



Alexandria Student Branch 119

This is a 1-by-4 vector whose elements are as follows:
[X of bottom-left corner Y of bottom-left corner Width Length].
These four elements are expressed in terms of the chosen units.
o String
This propertys value is a cell array of strings, each of which will be displayed on
a separate line and will be considered as an individual choice.
o BackgroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the popup menu background.
o ForegroundColor
This property is a 1-by-3 vector that defines the RGB intensities of the color of
the text appearing in the object.
o FontName
The font to be used for the text. Possible values are times, arial, courieretc.
o FontSize
A scalar defining the size of the font used for the objects text.
o FontWeight
This property has four values: [light | normal | demi | bold]. It determines how
thick the font is.
o Visible
This property determines the visibility of the object. It has two possible values: [
On | Off ].
o Enable
This property determines whether the object is active (allows user interaction) or
inactive (doesnt allow user interaction). It has two possible values: [ On | Off].
o Value
This propertys value holds the number of the selected line. Possible values are
integers ranging from 1 to the number of strings in the cell array.
o Tag
A characteristic name you choose to distinguish this object from all other objects.
o ToolTipString
Matlab Level 1 Summer 2008



Alexandria Student Branch 120

A help string in a yellow patch that appears whenever the user hovers with the
mouse pointer over the object in order to give him/her a tip about the item or how to
use it.

Obtaining Handles

After we have taken a look at the different types of H.G. objects and their
various properties, and after understanding the idea of handles, we wish to know how
we can deal with object handles. If we could reach a stage where we deal with handles
efficiently with no difficulties of complications, our next step would be to know to query
and modify objects properties.

Dealing with Handles Numerically

Handles in general are very long numbers, such as 120.6400000243. It is not a
good idea to deal with the handles as numbers. Not only are these numbers hard to
recall and to type in, but there is also the problem of not being able to know the exact
handle of an object. If Matlab tries to display the handle mentioned above, it will apply
the display round-off rule and will only display some not all of the decimal places. This
means that Matlab will show you the handle as 120.640. If you try to target an object
whose handle is 120.640, Matlab will tell you that no such object was found. This is
because the handle you enter as 120.640 will be interpreted by Matlab as
120.6400000000, which is not the correct handle you meant. The handle you mean
cannot be displayed accurately by Matlab due to display round-off rules that you define
for your convenience in your ordinary work. Therefore you cannot usually know the
correct numerical value of the handles.
It follows from the previous discussion that we will not be dealing numerically
with handles. We will store handles in variables, and call these variables whenever we
wish to deal with handles.

Obtaining Handles from the handles Structure

Every figure has a structure called handles that stores the values of its
childrens handles. This means that the structure handles contains the handles of all
the objects in the figure.

Suppose that we have a figure that contains two edit boxes for the user to enter
two numbers, a pushbutton for the sum calculation of the two numbers and a text box
for displaying the result. If the tags for the two edit boxes are num1 and num2, the
tag for the pushbutton is sum and that for the text box is result, then the handles for
Matlab Level 1 Summer 2008



Alexandria Student Branch 121

these four objects are stored in: handles.num1, handles.num2, handles.sum, and
handles.result.

If we wish to read the string entered in the second edit box, we need to know its
handle so as to be able to query its string property. We dont need to look for its
handle. It is already stored in handles.num2. Whenever we need to pass the handle,
we will pass the variable handle.num2. This variable contains the handle, so the
passing will achieve the desired effect.

Saving Handles for Plotted Objects

Suppose you have an axes plotbox in your figure, where your program will plot
surfaces or lines. These surfaces or lines will be created during program execution
after creating the figure, not during program design. This means that you as a
programmer dont have the chance to assign a tag to these objects during program
design. Additionally, these lines or surfaces do not yet exist during figure creation, and
this means that they have no entries in the handles structure. How could we grab hold
of these surfaces or lines handles?

We saw plotting commands of the form plot(x,y) or surf(x,y,z) before. If we
invoke any plotting command with an output argument such as line_handle=plot(x,y)
or surf_handle=surf(x,y,z), the plotting command will return the handle of the
resulting line or surface. Matlab will then assign these handles to the variables we
named line_handle or surf_handle. Whenever we need the handle for a line or a
surface, we may pass these variables.

Obtaining Handles using findobj

The function handle1=findobj(Property Name,Value) searches for the object(s)
whose property given by Property Name has the value given by Value, and return
its/their handle(s) in the variable handle1.

In some cases we dont want to search for the handle of an object given its tag,
but giving a certain parameter-value pair. In this case, we may use the findobj
function as described above to search for that object.


Some Special Handles

o The Root Handle
The root handle is always 0.

Matlab Level 1 Summer 2008



Alexandria Student Branch 122

o The Current Figure Handle
All figures have integer handles by default. If you have multiple figures together,
their handles are 1, 2, 3, according to their order of creation. A good way to get the
handle of the current (active) figure is to use gcf. gcf stands for get current figure.
You can pass gcf instead of the handle of the current figure.
o The Current Axes Handle
The current axes handle may be found using gca. gca stands for get current
axes. You can pass gca instead of the axes handle.














Matlab Level 1 Summer 2008



Alexandria Student Branch 123


Querying H.G. Object Properties

Using the Property Inspector during Program Design

If we deal with an object during design, we can double click on the object. This
will open a property inspector, which lists the objects properties and enables easy
reading and writing of the objects properties.

Using the get Instruction during Program Execution

During program execution, the programmer isnt sitting next to the user opening
the property inspector to query object properties. There must be an alternative fully-
automated mechanism of querying these properties. This is achieved by the get
instruction. The syntax is: A=get(handle, Property Name). This instruction gets the
value of the property whose name is Property Name for the object whose handle is
passed, and returns this value in the variable A.



Modifying H.G. Object Properties

Using the Property Inspector during Program Design

If we deal with an object during design, we can double click on the object. This
will open a property inspector, which lists the objects properties and enables easy
reading and writing of the objects properties.

Using the set Instruction during Program Execution

During program execution, the programmer isnt sitting next to the user opening
the property inspector to modify object properties. There must be an alternative fully-
automated mechanism of modifying these properties. This is achieved by the set
instruction. The syntax: set(handle, Property Name, Value). This instruction sets the
value of the property whose name is Property Name for the object whose handle is
passed to the value given in Value.

Matlab Level 1 Summer 2008



Alexandria Student Branch 124



Part 2: Matlab Graphical User Interfaces

What is a GUI?

The acronym GUI stands for Graphical User Interface. A GUI is a program that
displays in a graphical window (figure) and performs its tasks by interacting with the
user through an ensemble of objects (called UI controls) found in that figure.

GUIs provide a user friendly programming trend, specially that they dont require
the user of the program to operate in the Matlab environment. The GUI may be
designed to provide the user with guidance on how to use the program, and to isolate
the user from the Matlab code and routines.


Steps of Making GUIs

In order to make any GUI, there are two main steps. The first step is to layout
the GUI. This step is responsible for positioning the objects in their places and
configuring their properties. The second step is to program the GUI. This step is
responsible for constructing the mechanism by which the GUI operates. We will take a
closer look at each of these two steps in the following two sections. Also, we will apply
our discussion to making a very simple GUI that Prompts the user for two numbers,
and displays their sum when a pushbutton is pressed.

Step 1: Laying Out the GUI and Configuring Object Properties

This step is responsible for the visible aspect of the GUI, meaning that it
customizes the way the GUI will look to the user. This step may be further divided into
the following steps:
- Creating a new blank GUI
- Inserting Objects
- Configuring Object Properties
Matlab Level 1 Summer 2008



Alexandria Student Branch 125

- Aligning and Trimming Object Positions
- Saving the GUI

Creating a new Blank GUI
You can start a new GUI by typing (>>guide). A dialog will open prompting you
for the type of GUI to create. If you want to start with a GUI that already contains
some UI controls, choose the option GUI with UI Controls. In general, choose Blank
GUI to start a new empty GUI.

Inserting Objects
You insert objects by selecting their types from the object bar on the left side of
the screen in GUIDE, then clicking and dragging in the figure area. Ordinary rules of
cutting, copying and pasting apply under GUIDE. You can select multiple objects by
clicking and dragging the selection scope rectangle around those objects. You may use
the (Ctrl+x), (Ctrl+c) and (Ctrl+v) shortcuts for dealing with one or more selected
objects. You may also right click and drag one or more selected objects to create
duplicates of this/these object(s).

Configuring Object Properties
You configure object properties to achieve the following:
1. To give them the appearance and contents you wish
2. To give them the tags that help you in dealing easily with them in the
programming stage (step 2).

When working under GUIDE during the layout stage, you access object properties
through the property inspector. To open the property inspector to the properties of a
certain object, simply double click on that object, or right click and select the
properties option from the context menu.
If you want to establish some similar property configurations for a group of
objects, it would be more time efficient to access the properties of multiple objects at
once than to access the properties of those objects one by one. To edit properties for
multiple objects, select all the objects you want by first pressing and holding the Ctrl
key and then single clicking on the objects one by one. Afterwards, double click
anywhere on your selection and the property inspector will open. You can find
indication at the top of the property inspector that it is showing multiple-object
properties.
When you open the property inspector to multiple-object properties, the values
will show Multiple Values if the different objects have different values. If all objects
have the same value, this value will be displayed. If you write a value in the property
inspector when multiple objects are selected, the value you entered will apply to all of
those objects.
Matlab Level 1 Summer 2008



Alexandria Student Branch 126


Aligning and Trimming Object Positions
If you give your user a GUI whose object positions are not chosen carefully, the
GUI will look messy. To make the GUI look elegant and well organized, you must align
the objects and trim their positions.
You can initially obtain some aligning by making the objects snap to the grid.
Snapping to the grid is an option that can be enabled/disabled by right clicking
anywhere on the figure area but not over an object.
You can further align some objects by using the alignment tool after selecting
multiple objects to be aligned. This is an easy way once you understand how the
aligning is carried out.
The more professional, yet more complicated, way is to start by sketching the
GUI on a piece of paper and to set the units property of all objects to normalized,
then dimensioning the sketched GUI on paper. Afterwards, you can derive the position
vector for every object. You can then use multiple selection to apply the values of x, y,
width and height so that every object gets its position vector as you have planned.

Saving the GUI
When you save your GUI, the figure, objects and all properties are saved in a fig file.
This file contains the layout and property information of your GUI. After saving the GUI
with a suitable name, an M-File will appear with some preset code. This is the GUIs M-
File that you will program in the next step. The M-file gets the same name as the fig-
file. Note that it is incorrect to rename one or both of these files, because the name
used to match the fig- and M-files is also used internally in the code preset by Matlab
in the GUIs M-file. To rename a GUI, open it in GUIDE and choose Save as, then
enter the new name. After making sure the replicate is working properly, it is up to you
to delete the old file.

Step 2: Programming the GUI

Programming GUIs falls under a type called event-driven programming. Event-
driven programming means that segments of the program are executed in response to
certain events. In GUIs, events may correspond to user interaction with the GUI. Every
possible interaction of the user with the GUI can cause a certain block of code to
execute.
To start our discussion of programming GUIs, let us start by listing some
important events and functions that execute at those events.

Matlab Level 1 Summer 2008



Alexandria Student Branch 127

GUI Opening Function
This is a function that is executed right after the user runs the GUI but just
before the GUI is made visible.

Object Callback Functions
These are functions that execute when the user interacts with the objects. For
instance, a pushbutton callback is a function that executes whenever the user presses
the pushbutton. A popup menu callback is a function that executes whenever the user
changes selection in the menu. A radio button callback is a function that executes
whenever the user toggles the buttons state.

Closing Function
This is a function that is executed right after the GUI is made invisible but just
before its handles are totally destroyed.



If we wish to program a GUI, we must first have a clear and neat idea of what
tasks every event must do. Afterwards, we must write the pieces of code that
accomplish the desired tasks in their proper positions.

If you open a GUIs M-file, you will find that this M-file is like a template that
Matlab had prepared for you to simply fill in your code. You will find al the functions
related to your GUI listed in the M-File. All you have to do is to go under the proper
function declaration line and place the code.

Some important tips are worth being known when programming GUIs. We will
discuss some of these tips here.

String-Number Conversion
When the user enters a number in an edit box, we can query the string property
of the edit box to know what the user had entered. However, the number entered by
the user is still in string format and is not ready for mathematical processing. Also, if
we want to display a number in a text box, we cant the number as it is in its double
format to the string property of the text box. We need instructions that can change
strings to numbers and vice versa. The functions we will use are called str2num and
Matlab Level 1 Summer 2008



Alexandria Student Branch 128

num2str. The instruction A=num2str(4) returns the character 4 in A, and the
instruction B=str2num(A) returns the number 4 in B.
Passing Variables between Functions
Variables created inside a function are destroyed as soon as the function
execution is complete. If we want to pass a variable created in the callback of a radio
button to the callback of a pushbutton, we have to declare this global as global. Global
declaration takes the form (global var1 var2 var3 ). One important thing to notice
about global declaration of variables is that the first time the variable is declared as
global will initialize or reinitialize the variables value to []. Therefore, it is necessary to
start any function with the global declaration line right after the function declaration
line, to guarantee that the passed variable is not accidentally reinitialized.


Debugging & Running GUIs
After you finish writing code and saving the finalized M-file, you can start running the
GUI either by pressing the run button in the M-file editor or in GUIDE, or by typing the
GUI name at command prompt.

Your GUI may malfunction due to programming errors. In this case, you should
refer to debugging if you dont know exactly the source of the error. All debugging
tools are available for your use when debugging the GUIs M-file. More errors appear
when the GUI gets more and more complicated. The more experienced you become,
the less the errors you get.












Matlab Level 1 Summer 2008



Alexandria Student Branch 129

GUI Example 1: A Simple GUI that Adds 2 Numbers
It is required to design a simple GUI that contains four significant UI controls:
Two edit boxes for the numbers to be added, one pushbutton for the summation and
one text box for displaying the sum. Design and Program the GUI, then verify that it is
operating properly when it is supplied with valid input.

Solution

The tags used were as follows:
- For the first edit box: num1
- For the second edit box: num2
- For the summation pushbutton: add
- For the result textbox: sum

The programs consists of a single block of code written in the pushbuttons
callback:
N1=get(handles.num1, string); N1=str2num(N1);
N2=str2num(get(handles.num2, string));
set(handles.sum, string, num2str(N1+N2));



Matlab Level 1 Summer 2008



Alexandria Student Branch 130

Additional Information
GUIs with Multiple Figures

Some GUIs are more complicated than being designed in one figure. Such GUIs will
have to be designed in multiple figures. To do so, you need to know how to switch
from one GUI figure to the next.
Suppose that GUI0 and GUI1 belong to the same application. The user puts input in
GUI0 and views the results on GUI1. To switch between the two GUIs, you will need to
put a pushbutton on GUI0 which the user must click after he has supplied all required
inputs. You should write the following code in the callback of that
pushbutton. This will close the first GUI and open the next one.
close(gcf);
GUI1;

You will also need to know how to pass data between the two GUIs. To do so, look for
all the variables in GUI0 that need to be passed to GUI1. You should define these
variables as global variables in the functions in which they appear in GUI0 and in GUI1.
By doing this, you can access the contents of variables created in GUI0 from GUI1.



User Error Control
In a professional GUI, you have to perform checks to verify that the program is
running correctly.
Users may supply incorrect input, or input that may produce unwanted results or make
program running become unstable. To control input, you will need to use error,
warning, help and question dialogs. The
functions that do so are called "errordlg", "warndlg", "helpdlg" and "questdlg"
respectively. To see the syntax of these functions, refer to the documentation.

Matlab Level 1 Summer 2008



Alexandria Student Branch 131




Converting Matlab GUIs to EXEs

Matlab GUIs run under the Matlab environment. This is not always satisfactory.
Sometimes, the memory requirement of the program is high. When Matlab opens, its
active components reside in memory and occupy no less than 28Mb under medium
running. Under extensive running, the Matlab components might occupy even more
memory. These Megabytes might be better utilized if they were used to directly serve
the application directly. This urges us to convert our GUIs into a form that doesnt
need a running version of Matlab in order to execute. Such forms that do not require
the Matlab environment are called Stand-Alones. The most famous stand-alone
format is the win32 executable format (exe).


Generally speaking, we may be interested in converting Matlab GUIs to exe files for
the following four reasons:

1. The conversion leads to more efficient use of memory
2. The conversion leads to faster execution of the program
3. The conversion allows the program to run on any win32 compliant PC even if it
doesnt have Matlab, i.e. it makes the application more portable.
4. The conversion offers code secrecy because the M-File code is transformed to
irretrievable machine language.

In order to change a Matlab GUI into an EXE file, the following components are
required:
- Matlab (R13 is currently preferred.)
- Microsoft Visual C++ Compiler (Version 6.0 is preferred.)
Before starting with the steps of conversion, some setup and configuration is
required.
Matlab Level 1 Summer 2008



Alexandria Student Branch 132


o Pre-Configuration

1. Install Microsoft Visual C++ 6.0 (MSVC++ 6.0).
2. In the command prompt, execute the command (>> mbuild setup). Matlab will
provide you with a list of available compilers. If the MSVC++ installation was
successful, you shall see Microsoft Visual C++ Compiler Version 6.0 among the
listed compilers. Select it as your default compiler. Matlab will carry out some file
updates.
3. In the command prompt, execute the following two commands: (>>cd(prefdir);
mccsavepath;)
4. Open MSVC++ 6.0 then go to Tools -> Customize. Go to the Add-ins and Macro
Files part and select the Matlab Add-in, then click close. The Matlab toolbar
should appear as a result.

The pre-configuration is now complete.

o Building the EXE

The building stage is the stage which takes your M-Files and produces the
corresponding EXE file. The steps mentioned below should be followed.
1. Open MSVC++ 6.0 and go to File -> New.
2. Select the Project tab.
3. Select the Matlab Project Wizard option.
4. Make sure the project type shows Windows Console EXE.
5. Write down a unique name for your project in the project name edit box.
6. Press Next.
7. In the customization window, make sure the Handle Graphics support is
enabled and that C code is produced not C++ code.
8. Press Finish.
9. In the window that opens for the M-File selection, select the start-up M-file
from its location, then click open.
10. After the M-code is translated to C code, a progress text window will
open to give you a report about the translation process. Close this window.
11. Press Ctrl+F5 or go to Project -> Build EXE to produce the EXE file.

The EXE file is now ready. However, EXE files do not always run alone. Sometimes they
need some data files which diescribe images, sounds or graphical objects required
during their execution. As for a GUI, the EXE file doesnt contain information about the
GUIs figure. Hence, there are some additional files to be packaged with the EXE before
it may be run. The last stage is called Packaging, and it is responsible for assembling
all the required files together.
Matlab Level 1 Summer 2008



Alexandria Student Branch 133

o Packaging for Distribution

In order to produce a packaged program that you may run on any computer,
follow the steps mentioned below.
1. Copy all the GUI Fig files from their location to the bin folder in your
projects directory.
2. Copy any images, sounds or other external files to the bin folder.
3. Delete the Debug folder and all files that appear in the root of your
projects directory except the exe file.
4. Copy the file mglinstaller.exe from <Matlab>\extern\lib\win32 to your
projects directory.



o Running the EXE

If the target PC doesnt have Matlab, the user must first run the file
mglinstaller.exe. This file automatically extracts the required runtime libraries
required to run the program. This step shall only be done once per platform.
























Matlab Level 1 Summer 2008



Alexandria Student Branch 134

Session 6 Tasks

Task 1:
We want to design the following Plotting GUI

Matlab Level 1 Summer 2008



Alexandria Student Branch 135

You can select one of the three trigonometric function, enter the required frequency,
determine the required time range using the slider and click on the plot button.
You can turn grid on/off using the grid button and you can add another curve on the
same axes using add.





Task 2:
We want to generate the GUI of the following telephone pad.
When pressing any number button, the equivalent dtmf tone or pulse sound is
generated and played. When Play button is presses, the whole number is
played.
Use the Matlab function you have build in task 3 of session 5.
Matlab Level 1 Summer 2008



Alexandria Student Branch 136




Task 3:
Design the following GUI


Matlab Level 1 Summer 2008



Alexandria Student Branch 137

When pressing the Image Editor button the following GUI appears:



Which is used to open an image, display it, get its color component, convert it to gray
scale and save it.

When pressing the Sound Editor button the following GUI appears:

Matlab Level 1 Summer 2008



Alexandria Student Branch 138



Which is used to generate sound of single tone or mixed of two or three frequencies.
You can enter the wanted frequency or frequencies, the duration and the sampling
frequency. You can play this sound and save it to your hard disk.

You might also like