You are on page 1of 26

Introduction To Matlab

By Ehab Essa
Entering Matrices
MATLAB works with rectangular numerical matrix with possibly
complex entries;
– 1-by-1 matrices are interpreted as scalars and
– matrices with only one row or one column are interpreted as
vectors.
For example, either of the statements
A = [1 2 3; 4 5 6; 7 8 9]
and
A=[
123
456
789]
Constructing a Simple Matrix
• use the matrix constructor operator [ ] Create a row in the matrix by
entering elements (shown as E below) within the brackets. Separate
each element with a comma or space:
– row = [E1, E2, ..., Em] row = [E1 E2 ... Em]

• For example, to create a one row matrix of five elements, type


– A = [12 62 93 -8 22];

• To start a new row, terminate the current row with a semicolon:


– A = [row1; row2; ...; rown]
Specialized Matrix Functions
• MATLAB has a number of functions that create different kinds of
matrices.
Creating a Magic Square Matrix
To create a 5-by-5 magic square matrix,
A = magic(5)
A=
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

Note that the elements of each row, each column, and each main
diagonal add up to the same value: 65.
Creating a Random Matrix
The rand function creates a matrix or array with elements uniformly
distributed between zero and one.

This example multiplies each element by 20:


A = rand(5) * 20
A=
3.8686 13.9580 9.9310 13.2046 14.5423
13.6445 7.5675 17.9954 6.8394 6.1858
6.0553 17.2002 16.4326 5.7945 16.7699
10.8335 17.0731 12.8982 6.8239 11.3614
3.0175 11.8713 16.3595 10.6816 7.4083
Creating a Diagonal Matrix
You can place the vector along the main diagonal of the matrix, or on a
diagonal that is above or below the main one, as shown here.
The -1 input places the vector one row below the main diagonal:
A = [12 62 93 -8 22];
B = diag(A, -1)
B=
0 0 0 0 0 0
12 0 0 0 0 0
0 62 0 0 0 0
0 0 93 0 0 0
0 0 0 -8 0 0
0 0 0 0 22 0
Concatenating Matrices
• The brackets [ ] operator is also the MATLAB concatenation
operator. The expression C = [A B] horizontally concatenates
matrices A and B. The expression C = [A; B] vertically concatenates
them.

• If you are building a matrix horizontally, then each component matrix


must have the same number of rows.
• When building vertically, each component must have the same
number of columns.

This diagram shows two matrices


of the same number of rows being
combined horizontally
Generating a Numeric Sequence
The Colon Operator
• The colon operator (first:last) generates a 1-by-n matrix (or vector) of
sequential numbers from the first value to the last.
A = 10:15
A=
10 11 12 13 14 15

Using the Colon Operator with a Step Value


• (first:step:last). In between the starting and ending value is a step value that
tells MATLAB how much to increment (or decrement, if step is negative)
between each number it generates.
A = 10:5:50
A=
10 15 20 25 30 35 40 45 50
The Colon Operator
• A colon by itself denotes an entire row or column:
– A(:,3) is the third column of A, and A(1:4,:) is the first four rows.
• Arbitrary integral vectors can be used as subscripts:
– A(:,[2 4]) contains as columns, columns 2 and 4 of A.
M-files

• MATLAB can execute a sequence of statements stored in diskfiles.


Such les are called “M-files" because they must have the le type of
“.m" as the last part of their filename.
• There are two types of M-files: script files and function files.

Script files
• A script le consists of a sequence of normal MATLAB statements. If
the file has the filename, say, rotate.m, then the MATLAB command
rotate will cause the statements in the file to be executed.
• Variables in a script file are global and will change the value of
variables of the same name in the environment of the current
MATLAB session.
Function files
• We first illustrate with a simple example of a function file.
function a = randint(m,n)
%RANDINT Randomly generated integral matrix.
% randint(m,n) returns an m-by-n such matrix with entries
% between 0 and 9.
a = floor(10*rand(m,n));
• The first line declares the function name, input arguments, and
output arguments; without this line the le would be a script file.
Matrix operations
• The following matrix operations are available in MATLAB:
Array operations
• The matrix operations of addition and subtraction already operate
entry-wise but the other matrix operations given above do not they
are matrix operations.

• It is important to observe that these other operations *,^,\ and /, can


be made to operate entry-wise by preceding them by a period.

• For example,
– either [1,2,3,4].*[1,2,3,4] or [1,2,3,4].^2 will yield [1,4,9,16]. Try it.
Statements, expressions, and variables; saving a session

• MATLAB is an expression language. MATLAB statements are


usually of the form
variable = expression, or simply
expression

• Expressions are usually composed from operators, functions, and


variable names.

• Evaluation of the expression produces a matrix, and assigned to the


variable for future use. If the variable name and = sign are omitted,
a variable ans is automatically created to which the result is
assigned.
Statements, expressions, and variables; saving a session

• MATLAB is case-sensitive in the names of commands, functions,


and variables.

• The command who (or whos) will list the variables currently in the
workspace.

• A runaway display or computation can be stopped on most


machines without leaving MATLAB with CTRL-C (CTRL-BREAK ).

• When one exits MATLAB all variables are lost. However, invoking
the command save before exiting causes all variables to be written
diskle named matlab.mat. When one later re-enters MATLAB, the
command load
Control Flow

• To control the flow of commands, the makers of


MATLAB supplied four devices a programmer
• can use while writing code
– the for loops
– the while loops
– the if-else-end constructions
– the switch-case constructions
Repeating with for loops
• for Repeat statements a specific number of times.
• The general form of a FOR statement is:
– for variable = expr, statement, ..., statement end

• For example, for a given n, the statement


x = [ ]; for i = 1:10, x=[x,i^2], end
or
x = [ ];
for i = 1:10
x = [x,i^2]
end
Repeating with for loops
• Suppose that one-need values of the sine function at eleven evenly
spaced points n/10, for n = 0, 1, …, 10.
for n=0:10
x(n+1) = sin(pi*n/10);
end

• The for loops can be nested


H = zeros(5);
for k=1:5
for l=1:5
H(k,l) = 1/(k+l-1);
end
end
Repeating with While loops
• Syntax of the while loop is
while expression
statements
end
• This loop is used when the programmer does not know the number
of repetitions a priori.

• Suppose that the number is divided by 2. This process is continued


till the current quotient is less than or equal to 0.01. What is the
largest quotient that is greater than 0.01?
q = pi;
while q > 0.01
q = q/2;
end
the if-else-end constructions

• The general form of a simple if statement is


if relation
statements
end
• The statements will be executed only if the relation is true.
if n < 0
parity = 0;
elseif rem(n,2) == 0
parity = 2;
else
parity = 1;
end
Relations
• The relational operators in MATLAB are
< less than
> greater than
<= less than or equal
>= greater than or equal
== equal
~= not equal
• Relations may be connected by the logical operators
& and
| or
~ not.
Plotting
• The basic syntax to get a plot in matlab is plot(x1,y1)
– (The x values always come before the y values)

• If you type a second plot command later, it will clear your first plot.
– x = -4:.01:4; y = sin(x); plot(x,y)

• If you type "hold on" it will hold the current plot so you can add plots
on top of one another (until you reset it by typing "hold off".)

• you can specify the color and linetype of a plot as something like
plot(x1,y1,'w*') to get white *'s for each data point.
Plotting
• To split your plot into a bunch of smaller plots, you can use the
subplot command to split it up into rows and columns.
subplot(r,c,n)
• will split the plot window into r rows and c columns of plots and set
the current plot to plot number n of those rows and columns.

• For example, subplot(2,1,1) splits the plot window into two rows in a
single column and prepares to plot in the top plot. Then your plot
command will plot in the top plot. Then you could switch to the
bottom plot with subplot(2,1,2) and use another plot command to
plot in the bottom plot.
Plotting
• You can add titles, labels, and legends to plots.
title('This is a Title')
xlabel('My X axis')
ylabel('My Y axis')
legend('First Thing Plotted','Second Thing Plotted')
• legend creates a legend box (movable with the mouse) that
automatically uses the right symbols and colors and sticks the
descriptions in the legend command after them.

• The command grid will place grid lines on the current graph.
• Stem Plot discrete sequence data
– stem(y) plots the data sequence y as stems from the x-axis. Each stem
is terminated with a circle whose y-position represents the data value.
– stem(x,y) plots the data sequence y at the values specified in x.

• axis Axis scaling and appearance


– axis([xmin xmax ymin ymax]) sets the limits for the x- and y-axis of the
current axes.
– axis off / on

You might also like