Ios Rae3YoRVUlmi5Gc7
Ios Rae3YoRVUlmi5Gc7
College of Engineering
Materials Engineering Department
INTRODUCTION TO COMPUTER
PROGRAMMING
Contents
Chapter One: Introduction
1. General introduction
2. Basic features
3. A quick presentation on MATLAB
3.1 Starting MATLAB
3.2 Quitting MATLAB
4. Getting started
4.1 Creating MATLAB expressions
4.2 Hierarchy of arithmetic operations
4.3 Entering multiple statements per line
4.4 Output display format
4.5 Error messages
4.6 Getting help
5. Mathematical functions
Chapter Two: Plotting
1. Basic Plotting
1.1 Introduction
1.2 Creating a plot
1.3 Specifying line styles and colors
1.4 Multiple data sets in one plot
1.5 Plotting multiple plots seprately
1.6 Create graph with two y-axes
2. Stair Graph
3. Histogram Graph
4. Rose Graph
5. Pareto Chart
6. Area Graph (2D)
7. Pie Chart
8. 3D Graphs
8.1 3D Pie chart
8.2 3D Shaded surface plot
8.3 Sphere with two colors
9. Animating Plot
Chapter Three: Loops and Controlling Command
1. Introduction
2. Loops
2.1 Relational and logical operators
2.2 The for loop
2.3 The while loop
3. Controlling Command
3.1 The ``if...end'' structure
3.2 Return
3.3 Continue
3.4 Break
3.5 Switch and case
Chapter Four: Matrix
1. Entering a vector
2. Entering a matrix
3. Matrix indexing
4. Colon operator
5. Linear spacing
6. Colon operator in a matrix
7. Creating a sub-matrix
8. Deleting row or column
9. Dimension
10. Continuation
11. Transposing a matrix
12. Concatenating matrices
13. Matrix generators
14. Matrix functions
15. Matrix inverse
16. Mathematics operation for Matrix
Chapter One Introduction
Chapter One
Introduction
1. General introduction
This chapter is not intended to be a comprehensive manual of MATLAB. Our sole aim is
to provide sufficient information to give you a good start. The emphasis here is "learning
by doing". Therefore, the best way to learn is by trying it yourself. Working through the
examples will give you a feel for the way that MATLAB operates. In this introduction
we will describe how MATLAB handles simple numerical expressions and mathematical
formulas. The name MATLAB stands for MATrix LABoratory. MATLAB was written
originally to provide easy access to matrix software developed by the LINPACK (linear
system package) and EISPACK (Eigen system package) projects.
MATLAB is a high-performance language for technical computing. It integrates
computation, visualization, and programming environment. Furthermore, MATLAB is a
modern programming language environment: it has sophisticated data structures, contains
built-in editing and debugging tools, and supports object-oriented programming. These
factors make MATLAB an excellent tool for teaching and research.
2. Basic features
As we mentioned earlier, the following tutorial lessons are designed to get you started
quickly in MATLAB. The lessons are intended to make you familiar with the basics of
MATLAB. We urge you to complete the exercises given at the end of each lesson.
1
Chapter One Introduction
Normally when MATLAB is installed a MATLAB icon is installed onto the desktop,
you can enter MATLAB by double clicking on the MATLAB shortcut icon on your
Windows desktop. When you start MATLAB, a special window called the MATLAB
desktop appears. The desktop is a window that contains other windows as shown in
figure (1). The major tools within or accessible from the desktop are:
2
Chapter One Introduction
To end your MATLAB session, select Exit MATLAB from the File menu in the
desktop, or type (quit or exit) in the Command Window and next press Enter or Return
key.
4. Getting started
The goal of this section to learn how to assign values to variables, how to control the
appearance of floating point numbers on screen and other operations will study .
Where variable name begins with a letter, followed by letters, or numbers. MATLAB
is case sensitive; it distinguishes between uppercase and lowercase letters, A and a are
not the same variable Also, the expression is a combination of numerical values,
mathematical operators, variables, and function calls. For example,
>>x=1+2^2
x =
5
3
Chapter One Introduction
y =
47
Where a semicolon (;) put at the end of the line to suppress the numerical output when
you do not wish to see the intermediate results.
Note that the result of this expression is saved in variable whose name is chosen by you.
If it will be needed during your current MATLAB session, then you can obtain its value
typing its name and pressing the Enter or Return key. For example,
y
y =
47
If you want to clear the Command Window type clc and next press the Enter or Return
key.
+ Addition 2+3
- Subtraction -
2 3
* Multiplication 2*3
^ Exponentiation 2^3
4
Chapter One Introduction
First The contents of all parentheses are evaluated first, starting from
the innermost parentheses and working outward.
Second All exponentials are evaluated, working from left to right
By adding parentheses, below example gives different results for two expressions,
1 4 6
2 3 5 7
In MATLAB, it becomes
>>1/(2+3^2)+4/5*6/7
ans =
0.7766
>>1/2+3^2+4/5*6/7
ans =
10.1857
5
Chapter One Introduction
b =
0.7539
c =
548.3170
>> c
c=
548.3170
>> c
c =
5.483170351552120e+002
6
Chapter One Introduction
To return to the standard format, enter format short, or simply format. Another example
shown in the table 3 for the printed value of 10𝜋 in different formats.
Table 3: Output format
Formats Results
Format short 31.4159
Format short e 3.1416e+001
Format long 31.415926535897931
Format long e 3.141592653589793e+001
Format short g 31.416
Format long g 31.4159265358979
Format hex 403f 6a7a2955385e
Format rat 355/ 113
Format bank 31.42
>> x = 10 ;
>> 5 x
??? 5 x
To make corrections, we can, of course retype the expressions. But if the expression is
lengthy, we make more mistakes by typing a second time. A previously typed command
can be recalled with the up-arrow key . When the command is displayed at the command
prompt, it can be modified if needed and executed
7
Chapter One Introduction
The help command searches for an exact function name match. If you do not remember
the exact name of a function you want to learn more about use command lookfor
followed by the incomplete name of a function in the Command Window. In the
following example we will use the command lookfor that will produce detailed
information, which includes the function of interest.
>> lookfor sv
ISVMS True for the VMS version of MATLAB.
HSV2RGB Convert hue-saturation-value colors to red-green-blue.
RGB2HSV Convert red-green-blue colors to hue-saturation-value.
GSVD Generalized Singular Value Decomposition.
SVD Singular value decomposition.
SVDS Find a few singular values and vectors.
HSV Hue-saturation-value color map.
JET Variant of HSV.
CSVREAD Read a comma separated value file.
CSVWRITE Write a comma separated value file.
ISVARNAME Check for a valid variable name.
RANDSVD Random matrix with pre-assigned singular values.
Trusvibs.m: % Example: trusvibs
SVD Symbolic singular value decomposition.
RANDSVD Random matrix with pre-assigned singular values.
8
Chapter One Introduction
5. Mathematical functions
There are hundreds of functions in MATLAB. Typing help elfun and help
specfun calls up full lists of elementary and special functions respectively. The
common mathematical functions are listed in Table 4, where variables x and y can
be numbers, vectors, or matrices.
9
Chapter One Introduction
pi 𝜋 = 3.14159265…
i Imaginary unit, √ 1
j Same as i
eps Floating-point relative precision, 2-52
realmin Smallest floating-point number, 2-1022
Examples:
>> pi
ans=
3.1416
>> i
ans=
0.0000+1.0000i
10
Chapter One Introduction
>> j
ans=
0 .0000+1.0000i
>> Inf/Inf
ans=
NaN
Complex arithmetic is carried out with the normal arithmetic operators. MATLAB
automatically detects if a calculation contains complex numbers a n d c a r r i e s
o u t t h e appropriate calculation. There are also functions listed in table 6, that allow
you to obtain particular properties of the complex number.
Example:
>> s=3+4i
>> abs(s)
ans=
5
>>conj(s)
ans=
3.0000 - 4.0000i
>>imag(s)
ans=
4
11
Chapter One Introduction
Other command:
The who command displays all the variable names you have used.
who
MATLAB will execute the above statement and return the following result:
a ans b c x y
whos
MATLAB will execute the above statement and return the following result:
12
Chapter One Introduction
Exercises
Chapter One
Q1) Evaluate the following MATLAB expressions by hand and use
a) 2 / 2 * 3
b) 6 - 2 / 5 + 7 ^ 2 - 1
c) 10 / 2 \ 5 - 3 + 2 * 4
d) 3 ^ 2 / 4
e) 3 ^ 2 ^ 2
f) 2 + (6 / 9 + 3 * 2) / 2 - 3
a) 2, 4, 6, 8, ...
b) 10, 8, 6, 4, 2, 0, -2, -4
a) ln (2 + t + t )
t
b) e (1 + cos(3t))
2 2
c) cos (t) + sin (t)
-1
d) tan (1)
e) cot (t)
2
a) u = x + y
b) v = xy
c) w = x/y
d) z = w3
e) s = xy2/(x - y)
f) p = 3x/2y
g) r = 3xy/2
h) t = x5/(x5 - 1)
a) r = 8 sin(y)
b) s = 5 sin(2y)
c) z = sin(x)
d) w = 2(sin(x))/5
e) p = ex-1
f) u = 2 + cos(2πx)
g) m = √x + 4 + sin(0.2π) + e2
14
Chapter One Introduction
Q7) Evaluate the following expressions. You should have the format
short (the default) in effect for all but the last two items.
a) (a)1/0
b) (b)0/0
−8
c) (c)1 − 10
d) (d)1 − 10−20
−8
e) (e)1 – 10 with format long in effect
−20
f) (f )1 − 10 with format long in effect
a) (a2+ bc + x)
b) sin(c) + y/c
c) (a+c)/(x+y)
d) 1/(cos(c) + ln(x))
e) (a+c)3/b
15
Chapter One Introduction
16
Chapter Two Plotting
Chapter Two
Plotting
1. Basic plotting
1.1 Introduction
MATLAB has extensive facilities for displaying functions, vectors and matrices as
graphs, as well as annotating and printing these graphs. This section describes a few of
the most important graphics functions and provides examples of some typical
applications.
For example, these statements use the colon operator to create a vector of x values
ranging from zero to 2π, compute the sine of these values, plot the result, label the axes
and add a title.
>>x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine function')
17
Chapter Two Plotting
Another example, use the linspace command (Generate linearly spaced vectors) to
defined x as 100 linearly spaced values between 0 and 100.
>>x = linspace(0,100,100);
y =x.^2;
plot(x,y)
xlabel('x')
ylabel('y=x^2')
title('Plot of x versus y=x^2')
18
Chapter Two Plotting
It is possible to specify line styles, colors, and markers (e.g., circles, plus
signs,...) using the plot command:
19
Chapter Two Plotting
The example below shows how to specify the line style, color, and markers for two
sine waves. Plot the first sine wave with a blue dotted line 'b:'. Plot the second sine
wave with a red plus sign markers using 'r+'.
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin (x1), 'b:',x2,sin(x2), 'r+')
20
Chapter Two Plotting
Multiple x-y pair arguments create multiple graphs with a single call to plot. MATLAB
automatically cycles through a predefined list of colors to allow discrimination between
each set of data. For example, these statements plot three related functions of x, each
curve in a separate distinguishing color.
>>x=0:pi/100:2*pi;
y1=sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y1,x,y2,x,y3)
legend('sin(x)','sin(x-.25)','sin(x-.5)')
The legend command provides an easy way to identify the individual plots.
21
Chapter Two Plotting
In the above plot, MATLAB used default line style and color to distinguish the data sets
plotted in the graph. However, you can change the appearance of these graphic
components.
The subplot (row,column,index) command is used to plot multiple plots on the same
figure, but in separate views. subplot(2,2,4) means that the plot will be on the second
row, the second column, and the fourth index. For example
>> x = linspace (1,100,100);
y1 = x.^2;
y2 = log(x);
y3 = sin(x);
y4 = log10(x);
subplot(2,2,1), plot(x,y1)
subplot(2,2,2), plot(x,y2)
subplot(2,2,3), plot(x,y3)
subplot(2,2,4), plot(x,y4)
22
Chapter Two Plotting
In this example we will show how to create a graph with two y-axes, label the axes,
and display the grid lines. Create the data. Plot z1 versus t using semilogarithmic
scaling. Plot z2 versus t using linear scaling. Return the two axes objects as array ax.
Return the two lines as p1 and p2.
23
Chapter Two Plotting
The left y-axis corresponds to the first set of data plotted, which is the
semilogarithmic plot for z1. The first axes object, and the line p1, corresponds to the
first set of data.
The right y-axis corresponds to the second set of data plotted, which is the line plot
for z2. The second axes object, and the line p2, corresponds to the second set of data.
To add labels to the Axes, Label the x-axis and the left y-axis by passing the first
axes object to the xlabel and ylabel functions. Label the right y-axis by passing the
second axes object to the ylabel function.
xlabel(ax(1),'Time') % label x-axis
ylabel(ax(1),'Semilog Plot') % label left y-axis
ylabel(ax(2),'Linear Plot') % label right y-axis
24
Chapter Two Plotting
To modify line Appearance, we change the appearance of the lines. We can use dot
notation to set properties. If you are using an earlier release, use the set function
instead.
p1.LineStyle = '--';
p1.LineWidth = 2;
p2.LineWidth = 2;
Moreover, we can display a grid lines on the graph. Display the log grid associated
with the left y-axis by passing the first axes object to the grid function.
grid(ax(1),'on')
25
Chapter Two Plotting
2. Stair graph
To create a stair graph, we used a stairstep plot of y versus x. Then, we open a new
figure window using the figure command. If you do not open a new figure window,
then by default, MATLAB clears existing graphs and plots into the current figure.
Ex: plot a stair graph for x range (0 to 2π) and y is sine x function.
x = linspace (0, 2*pi, 25);
y = sin(x);
figure
stairs(x,y)
3. Histogram graph
The hist function shows the distribution of the elements in Y as a histogram with
equally spaced bins between the minimum and maximum values in Y. If Y is a vector
and is the only argument, hist creates up to 10 bins. For example:
Ex: Create a histogram showing 10 bins for each column in Y.
>> yn = randn(10000,1);
hist(yn)
Generates 10,000 random numbers and creates a histogram with 10 bins distributed
along the x-axis between the minimum and maximum values of yn.
26
Chapter Two Plotting
Matrix Input Argument, when Y is a matrix, hist creates a set of bins for each column,
displaying each set in a separate color. The statements
>> Y = randn(10000,3);
hist(Y)
27
Chapter Two Plotting
4. Rose graph
It's an angle histogram plot: rose (theta) creates an angle histogram, which is a polar
plot showing the distribution of values grouped according to their numeric range,
showing the distribution of theta in 20 angle bins or less. The vector theta, expressed
in radians, determines the angle of each bin from the origin. The length of each bin
reflects the number of elements in theta that fall within a group, which ranges from 0
to the greatest number of elements deposited in any one bin.
Ex: Create a rose plot showing the distribution of 50 random numbers.
5. Pareto chart
The Pareto charts display the values in the vector Y as bars drawn in descending
order. Values in Y must be nonnegative and not include NaNs. Only the first 95% of the
cumulative distribution is displayed. pareto (Y) labels each bar with its element index
in Y and also plots a line displaying the cumulative sum of Y.
Ex: Create a Pareto chart of vector y.
y = [90,75,30,60,5,40,40,5];
figure
pareto(y)
28
Chapter Two Plotting
An area graph displays elements in Y as one or more curves and fills the area
beneath each curve. When Y is a matrix, the curves are stacked showing the relative
contribution of each row element to the total height of the curve at each x interval.
area(Y) plots the vector Y or plots each column in matrix Y as a separate curve and
stacks the curves. The x-axis automatically scales to 1:size(Y,1).
Ex: Plot the data in matrix Y as an area graph.
Y = [1, 5, 3;
3, 2, 7;
1, 5, 3;
2, 6, 1];
figure
area(Y)
29
Chapter Two Plotting
7. Pie chart
The pie(X) function can draw a pie chart using the data in X. Each slice of the pie
chart represents an element in X.
❖ If sum (X) ≤ 1, then the values in X directly specify the areas of the pie slices.
pie draws only a partial pie if sum(X)< 1.
❖ If sum(X) > 1, then pie normalizes the values by X/sum(X) to determine
the area of each slice of the pie.
❖ If X is of data type categorical, the slices correspond to categories. The area of
each slice is the number of elements in the category divided by the number of
elements in X.
30
Chapter Two Plotting
8. 3D Graphs
31
Chapter Two Plotting
[X,Y,Z] = peaks(25);
figure
surf(X,Y,Z);
surf creates the surface plot from corresponding values in X, Y, and Z. If you do not
define the color data C, then surf uses Z to determine the color, so color is proportional
to surface height.
k = 5;
n = 2^k-1;
[x,y,z] = sphere(n);
c = hadamard(2^k);
figure
surf(x,y,z,c);
colormap([1 1 0; 0 1 1])
axis equal
32
Chapter Two Plotting
9. Animating plot
In this section, we will use only the comet3 function. There are many function in
MATLAB can be used in animating plot, but we will focus only on comet3. A comet
plot is an animated graph in which a circle (the comet head) traces the data points on
the screen. The comet body is a trailing segment that follows the head. The tail is a
solid line that traces the entire function. comet3(z) displays a 3-D comet graph of the
vector z.
t = -10*pi:pi/250:10*pi;
x = (cos(2*t).^2).*sin(t);
y = (sin(2*t).^2).*cos(t);
comet3(x,y,t);
33
Chapter Two Plotting
34
Chapter Two Plotting
COMMANDS
MATLAB is an interactive program for numerical computation and data
visualization. You can enter a command by typing it at the MATLAB prompt '>>'
on the Command Window.
In this section, we will provide lists of commonly used general MATLAB commands.
Purpose Command
Purpose Command
36
Chapter Two Plotting
Purpose Command
The fscanf and fprintf commands behave like C scanf and printf functions. They
support the following format codes:
Format as a string. %s
Format as an integer. %d
37
Chapter Two Plotting
The format function has the following forms used for numeric display:
Purpose Command
38
Chapter Two Plotting
39
Chapter Two Plotting
Plotting Commands
MATLAB provides numerous commands for plotting graphs. The following table
shows some of the commonly used commands for plotting:
Purpose Command
40
Chapter Two Plotting
41
Chapter Two Plotting
Exercises
Chapter Two
a) Plot y vs. x
b) Plot z vs. x
c) Plot w vs. x
d) Plot r vs. x
Q4) Create the vector x = randn (35,1) and then evaluate the
following function using only logical indexing:
y(x)= |sin x |
z(x)= |cos x |
You can check your answer by plotting y vs. x and z vs. x with
symbols.
Q7) Plot a graph y & z vs. x, with x from -5 to 10 with a step of 0.2
y= tan-1(x)
z= tan(x)
Q9) For the same x in Q8, Make some log and semi log plots of y
2 3
= x , and z = x . The commands to use are semilogx and loglog. To
create a vector of x3, type y = x.^3
Q11) Plot a cosine graph with x from 4 to 16, with step 0.4. Label the
x axis "degrees", label the y axis "cosine", and title the figure
"Exercise 11".
Q12) Plot, on the same figure, sine and cosine graph for x from 380
degrees to 986 degrees. The x axis should be in degrees. The sine plot
should be a magenta solid line with "o" markers at the data points.
The cosine plot should be a red dashed line with "*" markers at the
data points. Label the x axis "degrees", label the y axis "sine and
cosine", and title the figure "Exercise 12".
43
Chapter Three Loops and Controlling Command
Chapter Three
1. Introduction
When a particular numerical tasks needs to be “repeated” over different data points,
digital computers become a useful tool since they can do this with greater speed than
humans. Loops perform exactly these tasks. Using a condition to check the start and
termination rules, you can perform repetitive parts of a process easily. Different
programming languages and environments have different rules for defining loops.
MATLAB provides a much simpler way to define and run loops. They will be discussed
shortly. It’s useful to define the term function here. A big program may require a set of
instructions to be called at different times. Hence, these set of instructions can be defined
as a sub-program, which can be requested to perform the computation at a desired time. In
this way, a complicated task can be divided into many small parts. The most popular way
of defining these small sets of instructions is to define them as functions. This chapter
discusses both of these concepts in detail
2. Loops
Loops form an essential part of an algorithm since they perform the tasks that computers
perform best: doing repetitive actions very quickly. MATLAB come in two loops, the for
loop repeats certain tasks over a list of variable values, and the while loop checks a
logical condition before executing a certain task The choice of a particular loop depends
on the problem at hand.
44
Chapter Three Loops and Controlling Command
Operator Description
Greater than
Less than
Greater than or equal to
Less than or equal to
Equal to
~ Not equal
& And operator
׀ Or operator
~ Not operator
Note that the '' equal to" relational operator consists of two equal signs (==) (with no
space between them), since = is reserved for the assignment operator.
The keyword for declares the start of the loop where a variable takes the values stored
in a vector. Then the body of the code (here represented by BODY) is executed. The
keyword end declares the end of the for loop. This is explained in the following
example,
for i = 1 : 10
x = sqrt(i)
end
45
Chapter Three Loops and Controlling Command
It is a good idea to indent the loops for readability, especially when they are
nested. For example
H = zeros (5) ;
for j = 1 : 5
for i = 1 : 5
H(j,i) = 1/(j+i-1) ;
end
end
Note: if we need a step in or loop we put the number of the steps between the first and
last number of the loop : (for i = 1: 3 : 20) , so the first number in the loop is 1 and the
last number is 20. The steps will be 3 number in each loop.
The while loop defines a logical condition and, until it is satisfied, it runs a
block of code. The syntax for the while loop is:
while condition
Body
end
Here, the keyword while initiates the execution of a while loop. The condition is a logical
condition whose answer can be true (1) or false (0). The body encompasses a set of
commands that is executed until the condition holds true.
x=1;
while x <= 10
x = 3*x
end
46
Chapter Three Loops and Controlling Command
Note: If the condition inside the looping is not well defined, the looping will
continue indefinitely. If this happens, we can stop the execution by pressing Ctrl+C.
3. Controlling Command
if expression
statements
end
Examples
1) total = b * b-4 * a * c ;
if total < 0
disp ('total is negative value');
end
2) total = b * b-4 * a * c ;
if total < 0
disp ('total is negative value');
else
disp ('total is positive value')
end
47
Chapter Three Loops and Controlling Command
Notes:
❖ elseif has no space between else and if (one word).
❖ No semicolon (;) is needed at the end of lines containing if, else, end.
❖ Indentation of if block is not required, but facilitate the reading.
❖ The end statement is required.
3.2 Return
Return causes a normal return to the invoking function or to the keyboard. It also
terminates keyboard mode.
Example:
a = 0.5;
if a < 1
disp('Wrong parameters');
return
end
48
Chapter Three Loops and Controlling Command
3.3 Continue
It's used to pass control to next iteration of for or while loop. continue temporarily
interrupts the execution of a program loop, skipping any remaining statements in the
body of the loop for the current pass. The continue statement does not cause an
immediate exit from the loop as a break or return statement would do, but instead
continues within the loop for as long as the stated for or while condition holds true.
A continue statement in a nested loop behaves in the same manner. Execution
resumes at the for or while statement of the loop in which the continue statement was
encountered, and reenters the loop if the stated condition evaluates to true.
for i=1:5
disp('xi');
if i==3
continue
end
end
3.4 Break
The break statement lets you exit early from a for or while loop. In nested loops, break
exits from the innermost loop only.
1) for i=1:5
disp('xi');
if i==3
break
end
end
2) s=0;
for i=1:100
s=s+i;
if s>250
break
end
end
49
Chapter Three Loops and Controlling Command
switch expression
case1
statement,
case2
statement,
otherwise
statement,
end
Example: Write a code to convert x (cm) to any length untie type (in, f t, m , c m,
and mm).
x = 2.7;
units ='m';
switch units
case {'inch','in'}
y = x/2.54;
case {'feet','ft'}
y = x/(2.54*12);
case {'meter','m'}
y = x/100;
case {'centimeter','cm'}
y = x;
case {'millimeter','mm'}
y = x*10;
otherwise
disp(['Unknown Units: ' units])
y=NaN
end 50
Chapter Four Matrix
Chapter Four
Matrix
The fundamental unit of MATLAB is a matrix. In fact MATLAB is short for matrix
laboratory. However, its use is not restricted to matrix mathematics. Matrices in
MATLAB can also be regarded as arrays of numbers. You can regard matrices as a
convenient way of handling groups of numbers. A matrix in MATLAB can have one,
two or more dimensions. A matrix with a single element (column vectors (n=1) and
row vectors (m=1)) is a special case. They are treated as a single number. A matrix
element can be an integer, a real or a complex number. You do not have to worry about
element types. MATLAB will set the element type to what is required. Matrices that
contain a single row or column are called vectors. In this chapter we will demonstrate
how to apply different operations on matrices. The following topics are discussed:
vectors and matrices in MATLAB, the inverse of a matrix, determinants, and matrix
manipulation.
1. Entering a vector
A vector is a special case of a matrix. The purpose of this section is to show how to
create vectors in MATLAB. As discussed earlier, an array of dimension 1× n is
called a row vector, where as an array of dimension m×1 is called a column vector.
The elements of vectors in MATLAB are enclosed by square brackets. The
components of a row vector are separated by spaces or by commas, and of a column
vector by semicolon ( ; ). The examples below illustrate how vectors can be created in
MATLAB:
>> b = [ 1 2 3 4 5]
b=
1 2 3 4 5
>> b = [ 1, 2, 3, 4, 5]
b=
1 2 3 4 5
51
Chapter Four Matrix
>> b = [1 ; 2 ; 3 ; 4 ; 5]
b=
1
2
3
4
5
The single quote ( ' ) is the transpose operator in MATLAB; in the following example
b’ is the transpose of b.
Thus, b(1) is the first element of vector b, b(2) its second element, and so forth.
Furthermore, to access blocks of elements, we use MATLAB's colon notation (:). For
example, to access the first three elements of b, we write:
>> b(1:3)
ans =
1 2 3
Or, all elements from the third through the last elements:
>> b(3:end)
ans =
3 4 5
To replace element in the vector:
>> b(4)=7
ans =
1 2 3 7 5
52
Chapter Four Matrix
>> b=[b(1:5),2]
b=
1 2 3 4 5 2
>> b=[-1,b(1:5)]
b=
-1 1 2 3 4 5
Where end signifies the last element in the vector. If b is a vector, writing:
>> b(:)
Produces a column vector, whereas writing:
>> b(1:end)
Produces a row vector.
>> length(b)
ans=
5
>> c=sum(b)
c=
15
To find the maximum or minimum element of vector, we will use max or min
functions:
>> c=max(b)
c=
5
>> c=min(b)
c=
1
53
Chapter Four Matrix
For arrangement the elements of vector from minimum to maximum value, we will
use sort function:
>> w=[9 8 7 6 3]
w=
9 8 7 6 3
>>c=sort(w)
c=
3 6 7 8 9
2. Entering a matrix
Start by entering matrix as a list of its elements. You have only to follow a few basic
conventions:
1 2 3
𝐴= 4 5 6
7 8 9
>> A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
A=
1 2 3
4 5 6
7 8 9
Note that the use of semicolons ( ; ) here is different from their use mentioned earlier
to suppress output or to write multiple commands in a single line.
54
Chapter Four Matrix
This exactly matches the numbers in the engraving. Once you have entered the matrix,
it is automatically remembered in the MATLAB workspace. You can refer to it simply as
A. We can then view a particular element in a matrix by specifying its location. We
write:
>> A (3,2)
ans=
8
A (3,2) is an element located in the third row and second column. Its value is 8.
3. Matrix indexing
Once a matrix is created you might needed to access only a subset of the data.
This can be done with indexing. Each element of a matrix is indexed with the row
and column of the element. The entry in the ith row and jth column is denoted
mathematically by Ai;j and in MATLAB by A(i;j). For example, A(1,3) is an
element of first row and third column. Here, A(1,3) = 3.
Correcting any entry is easy through indexing. For the above matrix, we substitute
A(2,2) = 5 by A(2,2) = 0 .The result is:
>> A(2,2) = 0
A=
1 2 3
4 0 6
7 8 9
>> A(3,3) = 3
A=
1 2 3
4 5 6
7 8 3
55
Chapter Four Matrix
4. Colon operator
The colon operator allows you to create vectors with a sequence of values from the
start value to the stop value with a specified increment value. It occurs in several
different forms. Often we must deal with matrices or vectors that are too large to enter
one element at a time. For example, suppose we want to enter a vector b consisting of
points (0 ; 0.5 ; 1 ; 1.5 ; ….. ; 20 ). We can use the command:
>> b = 0 : 0.5 : 20 ;
5. Linear spacing
On the other hand, there is a command to generate linearly spaced vectors: linspace.
It is similar to the colon operator (:) , but gives direct control over the number of
points. For example:
y = linspace ( a , b )
Generates a row vector y of 100 points linearly spaced between and including a and b.
y = linspace ( a , b , n )
Generates a row vector y of n points linearly spaced between and including a and b.
This is useful when we want to divide an interval into a number of subintervals of the
same length. For example, to create vector with n equally spaced intervals:
>> x=linspace (0 , pi , 7)
x=
0 0.5236 1.0472 1.5708 2.0944 2.6180 3.1416
>> x= 0 :0.5:pi
x=
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000
56
Chapter Four Matrix
The colon operator can also be used to access the whole or a set consecutive elements
within a dimension of a matrix. For example, the statement C (m : n , k : l ) specifies
rows m to n and column k to l.
>> C(:,3)
ans =
6
5
9
12
The colon operator can also be used to extract a sub matrix from a matrix C.
Or
57
Chapter Four Matrix
7. Creating a sub-matrix
To extract a sub matrix B consisting of rows 2 and 3 and columns 1 and 2 of the
matrix A, do the following:
>> A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
A=
1 2 3
4 5 6
7 8 9
>> B = A ( [ 2 3 ] , [ 1 2 ] )
B=
4 5
7 8
Or
>> B = A (2 : 3), (1 : 2)
B=
4 5
7 8
To inter change rows 1 and 2 of A, use the vector of row indices together with the
colon operator.
>> C = A ( [ 2 1 3] , : )
C=
4 5 6
1 2 3
7 8 9
It is important to note that the colon operator (:) stands for all columns or all rows.
To create a vector version of matrix A, do the following:
58
Chapter Four Matrix
>> A( : )
ans=
1
4
7
2
5
8
3
6
9
As a special case, a colon (:) as the row or column specified covers all entries in that row
or column; thus
The key word end, used in A ( end , : ), denotes the last index in the specified
dimension.
For example:
>> A
A=
1 2 3
4 5 6
7 8 9
59
Chapter Four Matrix
Rows and columns can be deleted by assigning null matrices [] to them. For example,
(1,:)=[] deletes the first row and (:,1)=[] deletes the first column of a matrix.
>> A ( 3 , : ) = []
A=
1 2 3
4 5 6
Third row of matrix A is now deleted. To restore the third row, we use a technique for
creating a matrix
>> A= [ A( 1 , : ) ; A( 2 , : ) ; [ 7 8 9 ] ]
A=
1 2 3
4 5 6
7 8 9
Suppose you are having a matrix A and you want, ith row to be exchanged with jth
row. So the MATLAB command you will write is like: A([i j],:)=A([j i],:). The
following example show how you can exchange row 2 & 3,
A=
1 2 3
3 4 5
5 6 7
7 8 9
>>A([2 3],:)=A([3 2],:)
A=
1 2 3
5 6 7
3 4 5
7 8 9
60
Chapter Four Matrix
If you want to swap any row with the last row, & you don't know at what indices value
the last row belongs to, then you need to make the command like this A([i
end],:)=A([end i],:).
A=
1 2 3
7 8 9
5 6 7
3 4 5
Suppose you are having a matrix A and you want, ith column to be exchanged with
jth column. So the MATLAB command you will write is like: A(:,[i j])=A(:,[j i]).
The following example show how you can exchange columns 2 & 3,
A=
1 2 3
3 4 5
5 6 7
7 8 9
A=
1 3 2
3 5 4
5 7 6
7 9 8
If you want to swap any column 'i' with the last column, & you don't know at what
indices value the last column belongs to, then you need to make the command like this
A(:,[i end])=A(:,[end i]).
61
Chapter Four Matrix
9. Dimension
To determine the dimensions of a matrix or vector, use the command size. For
example:
>> size(A)
ans =
4 3
>> [m , n] = size(A)
m=
4
n=
3
10. Continuation
If it is not possible to type the entire input on the same line, use consecutive periods,
called an ellipsis …., to signal continuation, then continue the input on the next line.
Note that blank spaces around + , - , = signs are optional, but they improve
readability.
62
Chapter Four Matrix
The transpose of a matrix , denoted as AT, is the matrix that is obtained when the rows
and columns of matrix are interchanged. For example, if
1 4
1 2 3
A= then AT = 2 5
4 5 6
3 6
In MATLAB we use the apostrophe (′) symbol to denote and obtain the transpose of a
matrix. Thus, for the above example,
>>A=[1 2 3; 4 5 6]
A=
1 2 3
4 5 6
>> A'
ans =
1 4
2 5
3 6
63
Chapter Four Matrix
MATLAB provides functions that generate elementary matrices. The matrix of zeros,
the matrix of ones, and the identity matrix are returned by the functions zeros, ones,
and eye, respectively.
For a complete list of elementary matrices and matrix manipulations, type help elmat
or doc elmat. Here are some examples:
64
Chapter Four Matrix
3) >> c = zeros ( 2 , 3 )
c=
0 0 0
0 0 0
5) >> c = [1 2 3; 4 5 6; 7 8 9]
c=
1 2 3
4 5 6
7 8 9
>> diag(c)
ans =
1
5
9
>> C=[1 2; 3 4]
C=
1 2
3 4
65
Chapter Four Matrix
MATLAB provides many matrix functions for various matrix/vector manipulations; see
Table 11 for some of these functions. Use the online help of MATLAB to find how to
use these functions.
det Determinant
diag Diagonal matrices and diagonals of a matrix
eig Eigenvalues and eigenvectors
inv Matrix inverse
norm Matrix and vector norms
rank Number of linearly independent rows or columns
1 2 3
A= 4 5 6
7 8 0
Calculating the inverse of A manually is probably not a pleasant work. Here the hand
66
Chapter Four Matrix
16 8 1
A-1 14 7 2
1 2 1
>> A= [1 2 3 ; 4 5 6 ; 7 8 0];
>> inv(A)
ans =
16 8 1
A-1 14 7 2
1 2 1
67
Chapter Four Matrix
Two matrices (A and B) are conformable for addition (subtraction), if they are of the same
order m×n. If A and B are conformable for addition (subtraction), their sum (difference) will
be another matrix C with the same order as A and B, where each element of C is the sum
(difference) of the corresponding elements of A and B, that is,
1 2 3 2 3 0
A= and B=
0 1 4 1 2 5
>> C = A + B
C=
3 5 3
-1 3 9
>> D = A – B
D=
-1 -1 3
-1 -1 -1
If we like to know the summation of each column we use this code sum (A)
Where sum(A,1) use to compute the sum of each column, and sum(A,2) to sum each row.
68
Chapter Four Matrix
2) Matrix Multiplication
Two matrices are conformable for multiplication in that order, only when the number of
columns of matrix A is equal to the number of rows of matrix B.
C=A*B
For matrix multiplication, the operation is row by column. Thus, to obtain the product C,
we multiply each element of a row of A by the corresponding element of a column of B;
then, we add these products, For example
2 0
1 2 3
A= and B= 1 1
0 1 4
0 1
>> C = A * B
C=
4 5 𝟏∗𝟐 𝟐∗𝟏 𝟑∗𝟎 𝟏∗𝟎 𝟐∗𝟏 𝟑∗𝟏
A*B=
𝟎∗𝟐 𝟏∗𝟏 𝟒∗𝟎 𝟎∗𝟎 𝟏∗𝟏 𝟒∗𝟏
1 5
>> D= B * A
C=
2 4 6 𝟐∗𝟏 𝟎∗𝟎 𝟐∗𝟐 𝟎∗𝟏 𝟐∗𝟑 𝟎∗4
B*A= 𝟏 ∗ 𝟏 𝟏∗𝟎 𝟏∗𝟐 𝟏∗𝟏 𝟏∗𝟑 𝟏∗𝟒
1 3 7
𝟎∗𝟏 𝟏∗𝟎 𝟎∗𝟐 𝟏∗𝟏 𝟎∗𝟑 𝟏∗𝟒
0 1 4
7 1 2 2
A= 3 4 , B= 0 1
6 9 3 0
>> E = A.*B
E=
14 2
0 4
18 0
If one operand is a scalar and the other is a matrix, then MATLAB applies the scalar to
every element of matrix, see below example,
>> 3*A
ans =
21 3
9 12
18 27
Moreover, if we like to raise the matrix A to any power. The MATLAB can do it
easy. For example, suppose it is desired to form a matrix B from a matrix A by
raising each element of A to the 3rd power, The MATLAB command is:
>> B = A.^3
B=
343 1
27 64
216 729
70