0% found this document useful (0 votes)
13 views73 pages

Ios Rae3YoRVUlmi5Gc7

Uploaded by

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

Ios Rae3YoRVUlmi5Gc7

Uploaded by

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

University of Basrah

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.

3. A Quick Presentation on MATLAB


The goal of this minimum session (also called starting and exiting sessions) is to learn the
following:

 How to start MATLAB


 How to quit MATLAB

1
Chapter One Introduction

3.1 Starting MATLAB

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:

 The Command Window


 The Command History
 The Workspace
 The Current Directory
 The Help Browser
 The Start button

Figure1. The graphical interface to the MATLAB workspace

2
Chapter One Introduction

3.2 Quitting MATLAB

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 .

4.1 Creating MATLAB Expressions


MATLAB works as a calculator with mathematical operators shown in Table (1). To
perform a simple expression type a command into the command window and next press
the Enter or Return key. The double arrow on the left (>>) is the MATLAB prompt, will
appear after you have entered each expression. For example,
>>1+2^2
ans =
5

If you do not assign an expression to a variable, it is automatically assigned to a variable


called “ans” as shown in the above example. To avoid this, you may assign a value to a
variable as follow:

variable name=a value (or an expression)

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

Once a variable has been created, it can be reassigned. For example,


>> x = 5 ;

>> y = x^2 + 5*x -3

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.

Table 1: Basic arithmetic operators


Symbol Operation Example

+ Addition 2+3

- Subtraction -
2 3

* Multiplication 2*3

/ Right division 2/3

\ Left division 2\3

^ Exponentiation 2^3

4
Chapter One Introduction

4.2 Hierarchy of arithmetic operations


Power or exponentiation has precedence over all other arithmetic operations.
Multiplication and division have precedence over addition and subtraction. However,
the standard order of precedence of arithmetic operations can be changed by inserting
parentheses. Table 2 show the order in which the arithmetic operations are evaluated
using MATLAB.

Table 2: Hierarchy of arithmetic operations


Precedence Mathematical operations

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

Third All multiplications and divisions are evaluated, working from


left to right
All additions and subtractions are evaluated, starting
Fourth
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

or, if parentheses are missing,

>>1/2+3^2+4/5*6/7
ans =
10.1857

5
Chapter One Introduction

4.3 Entering multiple statements per line


It is possible to enter multiple statements per line. Use commas ( , ) or semicolons ( ; ) to
enter more than one statement at once. Commas ( , ) allow multiple statements per line
without suppressing output.

>> a = 7 ; b = cos ( a ) , c = cosh ( a )

b =

0.7539

c =

548.3170

4.4 Output display format


To change a format of numbers displayed in the Command Window you can use one of
the several formats that are available in MATLAB. The default format is called short
(four digits after the decimal point.) In order to display more digits click on File, select
Preferences…, and next select a format you wish to use. They are listed below the
Numeric Format. Next click on Apply and OK and close the current window. You can
also select a new format from within the Command Window. For example,

>> format short

>> c

c=

548.3170

If we want to see all 15 digits, we change a current format to format long

>> format long

>> 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

4.5 Error messages


If we enter an expression incorrectly, MATLAB will return an error message. For
example, in the following, we left out the multiplication sign ,*, in the following
expression

>> x = 10 ;

>> 5 x

??? 5 x

Error: Unexpected MATLAB expression.

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

4.6 Getting help


To view help, select Help from MATLAB toolbar or MATLAB Help directly in the
Command Window. The preferred method is to use the Help Browser. On the other
hand, to learn more about a function you want to use, type in the command window.
For example,

>> help svd


SVD Singular value decomposition.
[U,S,V] = SVD(X) produces a diagonal matrix S, of the same
dimension as X and with nonnegative diagonal elements in
decreasing order, and unitary matrices U and V so that
X = U*S*V'.
S = SVD(X) returns a vector containing the singular values.
[U,S,V] = SVD(X,0) produces the "economy size"
decomposition. If X is m-by-n with m > n, then only the
first n columns of U are computed and S is n-by-n.
See also SVDS, GSVD.
Overloaded methods
help sym/svd.m

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.

Table 4: Common mathematical functions

abs(x) Absolute value


sqrt(x) Square root.
round(x) Value rounded to the nearest integer.
rem(x,b) Remainder of x divided by b.
ceil(x) Round towards +∞
floor(x) Round towards -∞
sin(x) Sine
cos(x) cosine
tan(x) Tangent
asin(x) Arcsine. The inverse of sin(x)
acos(x) Arccosine
atan(x) Arctangent
exp(x) Exponential
log(x) Natural logarithm
log10(x) Common logarithm (log base 10)
sign(x) Signum function
max(x) Maximum value
min(x) Minimum value

Example: Evaluate the value of the expression y = sin 10 cos 10


>> y = sqrt(((sin(10))^2)+(cos(10))^2)
y=
1

9
Chapter One Introduction

Another examples are,


>> abs(-10.034)
ans=
10.034
>> log10(10)
ans=
1
>> asin(1)
ans=
1.5708
There are symbols in MATLAB that are indicate special numbers as listed in Table 5.

Table 5: Special number symbols

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

realmax Largest floating-point number, (2-𝜀)21023


Inf Infinity ∞
NaN Not-a-number

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.

Table 6: Complex numbers

real(A) The real part of A


imag(A) The imaginary part of A
conj(A) The complex conjugate of A
angle(A) The phase angle of A

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:

Your variables are:

a ans b c x y

 The whos command displays little more about the


variables: Variables currently in memory
Type of each variables
Memory allocated to each variable
Whether they are complex variables or not

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

MATLAB to check the answers:

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

Q2) Create a vector x with the elements:

a) 2, 4, 6, 8, ...

b) 10, 8, 6, 4, 2, 0, -2, -4

Q3) Given a vector, t , of length n , write down the MATLAB


expressions that
2 will correctly compute the following:

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

f) sec (t) + cot(t) - 1

Test that your solution works for t = 1:0.2:2 13


Chapter One Introduction

Q4) With x = 5 and y = 2, compute the following quantities:

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)

Q5) With x = 10 and y = 3, compute the following quantities:

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

Q6) Create a variable a and set a = ¼ + 3, Create b and set b = cos(a).

a) Type 'format long', and redisplay variable b. Does it look


different?

14
Chapter One Introduction

b) Type 'format short', and redisplay variable b. Does it look


different?

c) Calculate a * b. Calculate a + b. Calculate a/b.

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

Q8) Determine the result of the following calculations using

MATLAB if a = 2.3, b = -2.3, c= π/2, x =2/ π, and y = √3.

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

Q9) Create a MATLAB expression that calculates the logarithm base

10 of e raised to the power of 16.

Q10) Create a MATLAB expression that calculates the square root of

the sum of the sine of 24 degrees and the cosine of 56 degrees.

Q11) Create a MATLAB expression that calculates the tangent of 78

degrees and then raises this result to the power of 4.

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.

1.2 creating a plot


The plot function has different forms, depending on the input arguments. If y is a vector,
plot(y) produces a piecewise linear graph of the elements of y versus the index of the
elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y
versus x.

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

1.3 Specifying line styles and colors

It is possible to specify line styles, colors, and markers (e.g., circles, plus
signs,...) using the plot command:

plot ( x , y , ' style_color_marker ' )


If you don’t specify the line style and color, the plot will be in the default line style and
color (solid line and blue respectively). There are several style_color_marker options
listed in Table 7. To find additional information, type help plot or doc plot

Table 7: The plot command (Style, color and marker)

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+')

Another example, use the linspace command to defined x as 25 linearly spaced


values between 0 and . Plot the first sine wave with a green dashed line and
circle markers using '--go'. Plot the second sine wave with a red dotted line and star
markers using ':r*'.
>>x = linspace(0,2*pi,25);
y1 = sin(x);
y2 = sin(x-pi/4);
figure % new figure window
plot(x,y1,'--go',x,y2,':r*')

20
Chapter Two Plotting

1.4 Multiple data sets in one plot

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.

1.5 Plotting Multiple Plots Separately

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

1.6 Create Graph with Two y-Axes

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.

A = 1000 ; a = 0.005 ; b = 0.005 ; t = 0:900 ;


z1 = A*exp(-a*t);
z2 = sin(b*t);
[ax,p1,p2] = plotyy(t,z1,t,z2,'semilogy','plot');

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.

>> theta = 2*pi*rand(1,50);


rose(theta)

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

6. Area graph (2D)

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.

Ex: Create a pie chart of vector X.

X = [1 3 0.5 2.5 2];


pie(X)

X = [1 3 0.5 2.5 2];


Labels={‘first’,’second’,’third’,’fourth’,’fifth’}
pie(X,labels)

30
Chapter Two Plotting

8. 3D Graphs

8.1 3D pie chart


The function pie3(X) can draw a three-dimensional pie chart using the data in X. Each
element in X is represented as a slice in the pie chart.
❖ If sum(X) ≤ 1, then the values in X directly specify the area of the pie slices.
pie3 draws only a partial pie if sum(X)< 1.
❖ If the sum of the elements in X is greater than one, then pie3 normalizes
the values by X/sum(X) to determine the area of each slice of the pie.

Ex: Create a 3-D pie chart of vector x.


x = [1,3,0.5,2.5,2];
figure
pie3(x)

8.2 3D shaded surface plot

The surf(Z) function creates a three-dimensional shaded surface from the z


components in matrix Z, using x = 1:n and y = 1:m, where [m,n] = size(Z). The
height, Z, is a single-valued function defined over a geometrically rectangular
grid. Z specifies the color data, as well as surface height, so color is proportional to
surface height.
Ex: Use the peaks function to define X, Y, and Z as 25-by-25 matrices. Then, create
a surface plot.

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.

8.3 Sphere with Two Colors


Create a sphere and color it using the pattern from a Hadamard matrix, which is a
matrix that contains the values 1 and -1. Change the colors used in the plot by setting
the colormap to an array of two RGB triplet values.

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.

Ex: Create 3-D Comet Graph

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.

Commands for Managing a Session


MATLAB provides various commands for managing a session. The following table
provides all such commands:

Purpose Command

Clears command window. clc

Removes variables from memory. clear

Checks for existence of file or variable. exist

Declares variables to be global. global

Searches for a help topic. help

Searches help entries for a keyword. lookfor

Stops MATLAB. quit

Lists current variables. who

Lists current variables (long display). whos

Commands for Working with the System


MATLAB provides various useful commands for working with the system, like
saving the current work in the workspace as a file and loading the file later.
35
Chapter Two Plotting

It also provides various commands for other system-related activities like,


displaying date, listing files in the directory, displaying current directory, etc.

The following table displays some commonly used system-related commands:

Purpose Command

Changes current directory. cd

Displays current date. date

Deletes a file. delete

Switches on/off diary file recording. diary

Lists all files in current directory. dir

Loads workspace variables from a file. load

Displays search path. path

Displays current directory. pwd

Saves workspace variables in a file. save

Displays contents of a file. type

Lists all MATLAB files in the current directory. what

Reads .wk1 spreadsheet file. wklread

36
Chapter Two Plotting

Input and Output Commands


MATLAB provides the following input and output related commands:

Purpose Command

Displays contents of an array or string. disp

Read formatted data from a file. fscanf

Controls screen-display format. format

Performs formatted writes to screen or file. fprintf

Displays prompts and waits for input. input

Suppresses screen printing. ;

The fscanf and fprintf commands behave like C scanf and printf functions. They
support the following format codes:

Purpose Format Code

Format as a string. %s

Format as an integer. %d

Format as a floating point value. %f

Format as a floating point value in scientific notation. %e

Format in the most compact form: %f or %e. %g

Insert a new line in the output string. \n

Insert a tab in the output string. \t

37
Chapter Two Plotting

The format function has the following forms used for numeric display:

Display up to Format Function

Four decimal digits (default). format short

16 decimal digits. format long

Five digits plus exponent. format short e

16 digits plus exponents. format long e

Two decimal digits. format bank

Positive, negative, or zero. format +

Rational approximation. format rat

Suppresses some line feeds. format compact

Resets to less compact display mode. format loose

Vector, Matrix, and Array Commands


The following table shows various commands used for working with arrays,
matrices and vectors:

Purpose Command

Concatenates arrays. cat

Finds indices of nonzero elements. find

Computes number of elements. length

Creates regularly spaced vector. linspace

38
Chapter Two Plotting

Creates logarithmically spaced vector. logspace

Returns largest element. max

Returns smallest element. min

Product of each column. prod

Changes size. reshape

Computes array size. size

Sorts each column. sort

Sums each column. sum

Creates an identity matrix. eye

Creates an array of ones. ones

Creates an array of zeros. zeros

Computes matrix cross products. cross

Computes matrix dot products. dot

Computes determinant of an array. det

Computes inverse of a matrix. inv

Computes pseudoinverse of a matrix. pinv

Computes rank of a matrix. rank

Computes reduced row echelon form. rref

39
Chapter Two Plotting

Creates cell array. cell

Displays cell array. celldisp

Displays graphical representation of cell array. cellplot

Converts numeric array to cell array. num2cell

Matches input and output lists. deal

Identifies cell array. iscell

Plotting Commands
MATLAB provides numerous commands for plotting graphs. The following table
shows some of the commonly used commands for plotting:

Purpose Command

Sets axis limits. axis

Intelligent plotting of functions. fplot

Displays gridlines. grid

Generates xy plot. plot

Prints plot or saves plot to a file. print

Puts text at top of plot. title

Adds text label to x-axis. xlabel

Adds text label to y-axis. ylabel

Creates axes objects. axes

40
Chapter Two Plotting

Closes the current plot. close

Closes all plots. close all

Opens a new figure window. figure

Enables label placement by mouse. gtext

Freezes current plot. hold

Legend placement by mouse. legend

Redraws current figure window. refresh

Specifies properties of objects such as axes. set

Creates plots in sub windows. subplot

Places string in figure. text

Creates bar chart. bar

Creates log-log plot. loglog

Creates polar plot. polar

Creates semi log plot. (logarithmic abscissa). semilogx

Creates semi log plot. (logarithmic ordinate). semilogy

Creates stairs plot. stairs

Creates stem plot. stem

41
Chapter Two Plotting

Exercises
Chapter Two

Q1) What is drawn by the following code?


>> t = 0:0.01:6*pi;
>> y = cos(t);
>> plot(t,y)

What is the difference compared to


>> plot(y)

Q2) Enter a vector x = [0:0.1:20]; then create the vectors, y = sin(x);


z = sin(x/2); w = y + x; r = y-x; and

a) Plot y vs. x
b) Plot z vs. x
c) Plot w vs. x
d) Plot r vs. x

Q3) Plot the expression (determined in modeling the growth of the


US population)
-0.0313(t - 1913.25)
P(t) = (197273000)-1 × (1 + e )
Where t is the date, in years AD, using t = 1790 to 2000. What
Population is predicted in the year 2020?

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.

Q5) Evaluate the function tan(x) for x = 3 to x = 5 in step of 0.01


and make its plot.
42
Chapter Two Plotting

Q6) Let be the function y = sin(x2); x=from 0 to 2π


a) plot y vs. x
b) try making the step smaller (π/100),
c) add some labels (xlabel, ylabel),
d) and a title (title),
e) and a legend (legend),
f) finally add a grid (grid on).

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)

Q8) Obtain a hard copy of the plot of the functions Y = 2x , Z = 3x for


x = -1, …, 1 on the same axis. Label the x and y axes and creates a
legend indicating which graph is which.

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

Q10) Make a stair plot of the r = e0.2θ, θ ∈ [0, 5π].

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".

Q13) Make a 3D surface plot of the x, y, and z. Create the matrix


50×50 for x, y, and z. Add some labels, and check out the print
command.

43
Chapter Three Loops and Controlling Command

Chapter Three

Loops and Controlling Command

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.

2.1 Relational and logical operators


A relational operator compares two numbers by determining whether a comparison is
true or false. Relational operators are shown in Table 8.

44
Chapter Three Loops and Controlling Command

Table 8: Relational and logical operators

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.

2.2 The for loop


The for loop is used to perform computations on a list of known values. The syntax of
the for loop is:

for variable = vector


Body
end

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.

2.3 The while 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

3.1 The ''if...end'' Structure


MATLAB supports the variants of ''if" construct.
❖ if...end
❖ if...else...end
❖ if...elseif...else...end

The simplest form of the if statement is

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

disp is used to display text or array


3) total = b * b-4 * a * c ;
if total < 0 Syntax: disp(x)
disp ('total is negative value');
elseif total == 0 Description: disp(x) displays an array, without
printing the array name. If x contains a text
disp ('total is zero value') string, the string is displayed. Another way to
else display an array on the screen is to type its name,
disp ('total is positive value') but this prints a leading "x=," which is not
end always desirable. Note that disp does not display
empty arrays.

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

3.5 Switch and case


It's used to switch among several cases, based on expression. The switch statement
syntax is a means of conditionally executing code. In particular, switch executes one
set of statements selected from an arbitrary number of alternatives. Each alternative is
called a case. In its basic syntax, switch executes the statements associated with the
first case where switch_expr == case_expr. When the case expression is a cell array,
switch executes the case where any of the elements of the cell array matches the
switch expression. If there is no case expression matches the switch expression, then
control passes to the otherwise case (if it exists).

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.

>> b = [1 2 3 4 5]’ % Transpose of row vector


b=
1
2
3
4
5

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

To add element to the vector:

>> 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.

To evaluate the number of vector elements, we will use length function:

>> length(b)
ans=
5

To find summation of vector elements, we will use sum function:

>> 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:

 Separate the elements of a row with blanks or commas.


 Use a semicolon (;) to indicate the end of each row.
 Surround the entire list of elements with square brackets, [ ].

Here is a typical example. To enter a matrix A, such as:

1 2 3
𝐴= 4 5 6
7 8 9

To enter this matrix, simply type in command window,

>> A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]

MATLAB displays the matrix you just entered:

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

Single elements of a matrix are accessed as A(i,j), where i ≥ 1 and j ≥ 1. Zero or


negative subscripts are not supported in MATLA

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 ;

The row vector has 41 elements.

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

Divides the interval [ 0 ; π] into 6 equal subintervals, then creating a vector of


7 elements.

In other case, to create vector with equally spaced intervals

>> x= 0 :0.5:pi
x=
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000
56
Chapter Four Matrix

6. Colon operator in a 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=[1 3 6; 2 4 5; 7 8 9; 10 11 12]


C=
1 3 6
2 4 5
7 8 9
10 11 12

The elements on the third column of C can be accessed like:

>> C(:,3)
ans =
6
5
9
12

The colon operator can also be used to extract a sub matrix from a matrix C.

>> C (2:3, 2:3)


ans =
4 5
8 9

Or

>> C ([2 3], [2 3])


ans =
4 5
8 9

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

❖ A ( : , j ) is the jth column of A


❖ A ( i , : ) is the ith row of A
❖ A ( end , : ) picks out the last row of A

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

>> A ( end : -1 : 1 , end )


ans =
9
6
3

59
Chapter Four Matrix

8. Deleting row or column

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

For swapping matrix rows in MATLAB:

 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([2 end],:)=A([end 2],:)

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

For swapping matrix columns in MATLAB

 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(:,[2 3])=A(:,[3 2])

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

>>A(:,[1 end])=A(:,[end 1])


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

9. Dimension

To determine the dimensions of a matrix or vector, use the command size. For
example:

>> size(A)
ans =
4 3

Means 4 rows and 3 columns. Or more explicitly with:

>> [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.

B = [ 4/5 7.23 * tan(x) sqrt(6); ....


1/x^2 0 3/(x*log(x)) ; ....
x-7 sqrt(3) x*sin(x)];

Note that blank spaces around + , - , = signs are optional, but they improve
readability.

62
Chapter Four Matrix

11. Transposing a 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

12. Concatenating matrices

Matrices can be made up of sub-matrices. Here is an example. First, let's recall


ourprevious matrix A.
A=
1 2 3
4 5 6
7 8 9

The new matrix B will be:

63
Chapter Four Matrix

>> B=[A 10*A; -A [1 0 0; 0 1 0; 0 0 1]]


B=
1 2 3 10 20 30
4 5 6 40 50 60
7 8 9 70 80 90
-1 -2 -3 1 0 0
-4 -5 -6 0 1 0
-7 -8 -9 0 0 1

13. Matrix generators

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.

Table 9: Elementary matrices

eye(m,n) Returns an m-by-n matrix with 1 on the main diagonal


eye(n) Returns an n-by-n square identity matrix
zeros(m,n) Returns an m-by-n matrix of zeros
ones(m,n) Returns an m-by-n matrix of ones
diag(A) Extracts the diagonal of matrix A
rand(m,n) Returns an m-by-n matrix of random numbers

For a complete list of elementary matrices and matrix manipulations, type help elmat
or doc elmat. Here are some examples:

1) >> b = eye (3,3)


b=
1 0 0
0 1 0
0 0 1

64
Chapter Four Matrix

2) >> eye (3)


ans =
1 0 0
0 1 0
0 0 1

3) >> c = zeros ( 2 , 3 )
c=
0 0 0
0 0 0

4) >> b = ones (3,1)


b=
1
1
1

Equivalently, we can define b as >> b = [ 1 ; 1 ; 1 ]

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

In addition, matrices can be constructed in a block form, as follows:

>> C=[1 2; 3 4]
C=
1 2
3 4
65
Chapter Four Matrix

>> D=[C zeros(2); ones(2) eye(2)]


D= 𝐶 𝑧𝑒𝑟𝑜𝑠 2
1 2 0 0 𝑜𝑛𝑒𝑠 2 𝑒𝑦𝑒 2
3 4 0 0
1 1 1 0
1 1 0 1

14. Matrix functions

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.

Table 11: Matrix 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

15. Matrix Inverse

Let's consider the same matrix A.

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

calculation of A-1 gives as a final result:

66
Chapter Four Matrix

16 8 1
A-1 14 7 2
1 2 1

In MATLAB, however, it becomes as simple as the following commands:

>> A= [1 2 3 ; 4 5 6 ; 7 8 0];

>> inv(A)

ans =

-1.7778 0.8889 -0.1111


1.5556 -0.7778 0.2222
-0.1111 0.2222 -0.1111

This is similar to:

16 8 1
A-1 14 7 2
1 2 1

And the determinant of A is


>> det (A)
ans=
27

67
Chapter Four Matrix

16.Mathematics operation for Matrix

1) Matrix Addition and Subtraction

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)

>> sum (A)


ans =
1 3 7
If we like to know the summation of each row we use this code sum (A,n).

>> sum (A,2)


ans =
6
5

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

But Multiplication of B*A will produce a 3×3 matrix as follows,

>> D= B * A

C=
2 4 6 𝟐∗𝟏 𝟎∗𝟎 𝟐∗𝟐 𝟎∗𝟏 𝟐∗𝟑 𝟎∗4
B*A= 𝟏 ∗ 𝟏 𝟏∗𝟎 𝟏∗𝟐 𝟏∗𝟏 𝟏∗𝟑 𝟏∗𝟒
1 3 7
𝟎∗𝟏 𝟏∗𝟎 𝟎∗𝟐 𝟏∗𝟏 𝟎∗𝟑 𝟏∗𝟒
0 1 4

There is another form of multiplication of matrices in which it is desired to multiply


corresponding elements in a fashion similar to that of addition and subtraction. This
operation arises frequently with MATLAB, and we will refer to the process as the
array product to distinguish it from the standard matrix multiplication form. For the
array product to be possible, the two matrices must have the same size, as was the case
for addition and subtraction. The resulting array product will have the same size.
If there are more than two matrices for which array multiplication is desired, the
periods should follow all but the last one in the expression; e. g.: A.*B.*C in the case
of three matrices. Alternately, nesting can be used; e.g.: (A.*B).*C for the case of
three matrices.
69
Chapter Four Matrix

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

You might also like