Lab 2 - NA
Lab 2 - NA
LAB 2
Fundamental Concepts
Objective
The aim of this introductory lab is to introduce you to the basic functions in the
Matlab and Numerical Methods with Matlab toolbox. By the end of today’s lab, you
should be able to understand the Arrays Creation, Arrays Access, the Arrays
operations, Element by element on Arrays.
Submission Requirements
You are expected to complete the assigned tasks within the lab session and show
them to the lab engineer/instructor. Some of these tasks are for practice purposes
only while others (marked as ‘Exercise’ or ‘Question’) have to be answered in the form
of a lab report that you need to prepare. Following guidelines will be helpful to you in
carrying out the tasks and preparing the lab report.
Guidelines
• In the exercises, you have to put the output in your Lab report. You may add
screen print to the report by using the ‘Print Screen’ command on your
keyboard to get a snapshot of the displayed output. This point will become
clear to you once you actually carry out the assigned tasks.
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 1
MTH-331 Numerical Analysis Lab 2
Creating Matrix/Arrays
The Matrix/Array is a fundamental form that Matlab uses to store and manipulate data. It is a list of
numbers arranged in rows and/or columns. Simplest way to create matrix is to use the constructor
operator [ ].
One Dimensional
It is a list of numbers that is placed in a row or a column.
Variable_name=[ type vector elements ]
Row Vector: To create a row vector type the element with a space or a comma between the elements
inside square brackets.
row = [E1, E2, … Em] or row = [E1 E2 … Em]
>>A=[12, 62, 93, -8, 22]
Column Vector: To create a column vector type the element with a semicolon between the element
or press the enter key after each element inside square brackets.
col = [E1; E2; … Em] or row = [E1
E2
… Em]
>>B=[12; 62; 93; -8; 22]
Example Date
Year 2007 2008 2009 2010
Population 136 158 178 211
(Millions
Practice 1
>> yr=[2007 2008 2009 2010] %Year is assigned to a row vector named yr.
yr = 2007 2008 2009 2010
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 2
MTH-331 Numerical Analysis Lab 2
Where start is first term, stop is last term and step is spacing between elements. The default
value of step is 1.
Practice 2
>> yr=[2007 : 2010] %Year is assigned to a row vector named yr.
yr = 2007 2008 2009 2010
Note: If stop value can not be obtained by add step’s to stop then the last element is the vector with be
last number that does not exceed stop.
Matrix creation using linspace function
The linspace function is used to generate a row vector of n linearly equally spaced elements.
Variable_name=linspace( start, stop, n)
Where start is first element, stop is last element and n is the total number of elements are
created. The default value of n is 100.
Practice 3
>> x=linspace(0,1); %100 equally spaced elements are created
To create a matrix type the element with a semicolon between the rows or press the enter key after
each row inside square brackets.
row = [RE1; RE2; … REm] or row = [RE1
RE2
… REm]
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 3
MTH-331 Numerical Analysis Lab 2
Practice 4
>> a=[5 35 43; 4 76 81; 21 32 40] %A semicolon is typed before a new line
Special Matrix
zeros(n) n × n-matrix will be created and all elements are zero.
zeros(m,n) m × n-matrix will be created and all elements are zero.
ones(n) n × n-matrix will be created and all elements are one.
ones(m,n) m × n-matrix will be created and all elements are one.
eye(n) n × n-matrix will be created and diagonal elements are one (identity matrix).
diag(V) Creates a square matrix with the elements of vector V in the diagonal
diag(M) Creates a column vector with the diagonal elements of matrix M
triu(M) Extract upper triangular part of matrix M
triul(M) Extract lower triangular part of matrix M
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 4
MTH-331 Numerical Analysis Lab 2
Practice 6
>> aa=[3 8 1]; %Define a row vector aa.
Array Addressing
Elements in an array (either vector or matrix) can be addressed individually or in subgroups.
Vector Addressing
• The address of an element in a vector is its position in the row or column.
• A vector named ve, ve(k) refers to the element in position k.
• The first position is 1.
• You can change the value of any element by address like this v(k)=new value.
Practice 7
>> VCT=[35 46 78 23 5 14 81 3 55]; %Define a vector
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 5
MTH-331 Numerical Analysis Lab 2
Matrix Addressing
• The address of an element in a matrix is its position defined by the row and column.
• A matrix named ma, ma(k,p) refers to the element in row k and column p.
• The first row and column position is 1.
• You can change the value of any element by address like this ma(k,p)=new value.
Practice 8
>> MAT=[3 11 6 5; 4 7 10 2; 13 9 0 8]; %Create a 3x4 matrix
Practice 9
>> ve=[4 15 8 12 34 2 50 23 11]; %A vector ve is created
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 6
MTH-331 Numerical Analysis Lab 2
Practice 10
>> ma=[1 3 5 7 9 11; 2 4 6 8 10 12; 3 6 9 12 15 18; 4 8 12 16 20 24; 5 10 15 20 25 30];
Important
>> v=4:3:34;
>>u=v([3, 5, 7:10]) % u is created with 3rd, the 5th and 7th to 10th element of v
u= 10 16 22 25 28 31
Adding element to existing array
A variable can be changed by adding elements to it .
A vector can be changed to have more elements or it can be changed to be a tow-dimensional
The addition of elements can be done by simply assigning values to the additional elements.
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 7
MTH-331 Numerical Analysis Lab 2
Practice 11
>> DF=1:4;
>> AR(5)=24 %{Assign a value to the 5th element of new vector and
Matlab assigns zeros to 1st to 4th elements}%
AR= 0 0 0 0 24
Practice 12
>> E=[1 2 3 4; 5 6 7 8];
>>E(3,:)=[10:4:22] %Add the vector 10 14 18 22 as the third row of E
E= 1 2 3 4
5 6 7 8
10 14 18 22
>>G=[E K]
E= 1 2 3 4 1 0 0
5 6 7 8 0 1 0
10 14 18 22 0 0 1
>>AW=[3 6 9; 8 5 11];
>>AW(4,5)=17; %Matlab changes the matrix size to 4x5 and assigns zeros to new elements
>>BG(3,4)=15; %Matlab creates 3x4 matrix and assigns zeros to elements except BG(3,4)
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 8
MTH-331 Numerical Analysis Lab 2
Deleting Elements
An element or a rang of elements, of an existing variable can be deleted by reassigning
nothing to these element.
This can be done by using square brackets with nothing typed in between them.
Practice 13
>> kt=[2 8 40 65 3 55 23 15 75 80];
Arrays Built in Function
Function Description Example
length(A) Returns the number of elements in the >>A=[5 9 2 4];
>>length(A)
vector A.
ans=4
size(A) Returns a row vector [m,n], where m and n >>A=[6 1 4 0 12; 5 19 6 8 2];
>>size(A)
are the size m x n of array A
ans=2 5
reshape(A,m,n) Rearrange a matrix A that has r rows and s >>A=[5 1 6; 8 0 2];
>>B=reshape(A,3,2)
columns to have m rows and n columns. r
B= 5 0
times s must be equal to m times n. 8 6
1 2
Strings and Strings as variable
• A string is an array of characters. It is created by typing the characters within single
quotes
• String can include letters, digits, other symbols and spaces.
• A string that contains a single quote is created by typing two single quotes within string.
• Matlab has built in function named char that creates an array with rows that have the same
number of characters, length all the rows equal to the longest row by adding spaces at the
end of short lines.
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 9
MTH-331 Numerical Analysis Lab 2
Practice 14
>> B=’My name is Shahid’
B= My name is Shahid
>> B(4)
ans=n
>> B(12)
ans=S
>> B(12:17)=’Khalid’
B= My name is Khalid
>>Info=char(‘Student Name:’,’Shahid’,’Grade:’,’A+’); %Variable Info is of different strings
Note: Function char creates an array with four rows with the same lenght as the longes row by
adding empty spaces to the shorter lines.
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 10
MTH-331 Numerical Analysis Lab 2
Addition and Subtraction
• The operations addition and subtraction can be used with array of identical (Same order)
size.
• The sum or difference of two array is obtained by adding or subtracting their
corresponding elements.
• When a scalar is added to or subtracted from an array the number is add or subtracted
from all the elements of the array.
Practice 15
>> VectA=[8 5 4];
>> C=A+B
C= 15 4 12
-2 17 11
>> D=A-B
D= -5 -10 4
20 -13 9
>> C-8
ans= 7 -4 4
-10 9 3
Array Multiplication
• Multiplication operation is executed by Matlab according to the rules of linear algebra.
• If A and B are two matrices, the operation A*B can be carried out only if the number of
columns in matrix A is equal to the number of rows in matrix B.
• If A and B are both nxn then A*B not equal to B*A
• Power operation can only be executed with a square matrix
• Two vectors can be multiplied if both have the same number of elements, and one is a row
vector and the other is column vector.
• An array is multiplied by a number then each element in the array is multiplied by the
number
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 11
MTH-331 Numerical Analysis Lab 2
Practice 16
>> A=[1 4 2; 5 7 3; 9 1 6; 4 2 8];
>> C= A*B
C= 28 27
65 49
98 32
84 38
>> D=B*A;
???Error using Î*
Inner matrix dimensions must agree.
>> F*G
ans= 7 20
27 52
>> G*F
ans= 14 26
31 45
>>b=3;
>>C=b*A
C= 6 15 21 0
30 3 9 12
18 6 33 15
Array Division
• The division operation can be done with the help of the identity matrix and the inverse
operation.
• eye() is used to create Identity matrix, if a matrix A is square, it can be multiplied by the
identity matrix I, from the left or from the right. (A*I = I*A = I)
• inv() is used to find inverse of matrix. The matrix B is the inverse of the matrix A if when
the two matrices are multiplied the product is the identity matrix.(B*A = A*B = I, B=A-1)
• det() is used to find determinant of matrix. Not every matrix has an inverse. A matrix has
an inverse only if it is square and its determinant is not equal to zero.
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 12
MTH-331 Numerical Analysis Lab 2
Practice 17
>> A=[2 1 4; 4 1 8; 2 -1 3];
Element by element operation
• When operation applied on each element is said to be element by element. Addition and
subtraction are by definition already element by element operations but multiplication,
division and exponential are done by using . (dot) operator.
• This operation is applied on two arrays then must be the same size of both arrays but one
of them can be a scalar.
• If two vectors a and b are: a=[a1 a2 a3] and b=[b1 b2 b3] then element by element of the two
vectors as follows
a.*b = [a1*b1 a2*b2 a3*b3] a./b = [a1/b1 a2/b2 a3/b3] a.^b = [a1^b1 a2^b2 a3^b3]
Symbol Description Symbol Description
.* Multiplication ./ Right division
.^ Exponential .\ Left division
Practice 18
>> A=[2 6 3; 5 8 4];
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 13
MTH-331 Numerical Analysis Lab 2
Built in function for analyzing Arrays
Function Description Example
mean(A) If A is a vector, returns the mean value of >>A=[5 9 2 4];
>>mean(A)
the elements of the vector
ans=5
C=max(A) If A is a vector, C is the largest element in >>A=[5 9 2 4 11 6 7 11 0 1];
>>C=max(A)
A. If A is a matrix, C is a row vector
ans=11
containg the largest element of each
column of A.
[d,n]=max(A) If A is a vector, d is the largest element in >>[d,n]=max(A)
d=11
A, n is the position of the element
n=5
C=min(A) The same as max(A), but for the smallest >>A=[5 9 2 4];
>>C=min(A)
element.
C=2
[d,n]=min(A) The same as [d,n]=max(A), but for the
smallest element.
C=sum(A) If A is a vector, returns the sum of the >>A=[5 9 2 4];
>>C=sum(A)
element of the vector
C=2
sort(A) If A is a vector, arranges the element of the >>A=[5 9 2 4];
>>sort(A)
vector in ascending order
ans=2 4 5 9
C=median(A) If A is a vector, returns the median value of >>A=[5 9 2 4];
>>C=median(A)
the elements of the vector
C=4.5000
C=std(A) If A is a vector, returns the standard >>A=[5 9 2 4];
>>C=std(A)
deviation of the elements of the vector.
C=2.9439
rand Generates a single random number >>rand
Ans=0.2311
between 0 and 1
rand(1,n) Generates an n elements row vector of >>a=rand(1,4);
random numbers between 0 and 1
rand(n) Generates an n x n matrix with random >>b=rand(3);
numbers between 0 and 1
rand(m,n) Generates an m x n matrix with random >>c=rand(2,4)
numbers between 0 and 1
Randperm(n) Genereates a row vector with n elements >>randperm(8)
Ans= 8 2 7 4 3 6 5 1
that are random permutation of integers 1
to n
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 14
MTH-331 Numerical Analysis Lab 2
Exercise 1
Use Matlab to show that the sum of the infinite series sum(1/n2) converges to
Exercise 2
Solve the following system of foure linear equations
5x+4y-2z+6w=4
3x+6y+6z+4.5w=13.5
6x+12y-2z+16w=20
4x-2y+2z-4w=6
Graphics
MATLAB produce two and three dimensional plots of curves and surface
Two Dimensional Plots
• Plots are very useful tool for presenting information.
• Plot title, Legend, X axis label, Y axis label, Text label and Markers.
• Graph is shown in figure window.
Plot Command
The plot command is used to create two dim plots.
The simplest from of the command is plot(x,y), Where x (horizental axis) and y (vertical axis)
are vector.
Both vectors must have the same number of elements.
The curve is constructed of straight line segments that connect the points.
The figure that is created has axes with linear scale and default range.
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 15
MTH-331 Numerical Analysis Lab 2
Practice 20
>> x=[1 2 3 5 7 7.5 8 10];
>>plot(x,y)
Line Specifiers:
• Line specifiers are optional and can be used to define the style and coloar of the line and
the type of markers.
• Within the string the specifiers can be typed in any order.
• Specifier is optional i.e. None, one, two, or all the three can be included in command.
Practice 21
>>plot(x,y,’r’);
>>plot(x,y,’--y’);
>>plot(x,y,’*’);
>>plot(x,y,’g:d’);
>>plot(x,y,’-mo’,’LineWidth’,2,’markersize’,12,’MarkerEdgeColor’,’g’,’markerfacecolor’,’y’);
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 16
MTH-331 Numerical Analysis Lab 2
Plot of function
Plot of given functgion can be done in Matlab by using the plot or the fplot commands.
Using plot: Plot a function y=f(x) with plot command, user first needs to create a vector of
values of x for the domain that function will be plotted.
Then a vector y is created with the corresponding values of f(x) by using element by element
calculation
Plot the x and y vectors by using plot command.
Using fplot: Plot a function y=f(x) with fplot command between specified limits.
function can be typed directly as a string and The function can not inclue prefiouly defined
variables.
limits is a vector with two element that specify the domain of x [xmin,xmax] or
[xmin,xmax,ymin,ymax].
n is the number of points between interval.
Line specifier are the same as in plot command.
Practice 22
Examples: y=3.5-0.5xcos(6x) for -2<=x<=4 and y=cos(x), z=cos(x)2 for 0<=x<=pi
>>x=[-2:0.01:4]; %Create vector x with domain of function
>>y=3.5.^(-0.5*x).*cos(6*x); %Create vector y with funtion value at each x
>>plot(x,y);
%Two or more graphs can be created in the same plot by typing pairs of vectros.
>>x=0:0.1:pi; % specifies the domain
>>y=cos(x); % define 1st function
>>z=cos(x).^2; % define 2nd function
>>plot(x,y,x,z,’o’) % display graph. (x, y 1st fun , x, y 2nd fun )
Examples: plot of function y=3x3-26x+10, and its first and second derivatives for -2<=x<=4
>>x=[-2:0.01:4];
>>y=3*x.^3-26*x+6;
>>yd=9*x.^2-26;
>>ydd=18*x;
>>plot(x,y,’-b’,x,yd,’—r’,x,ydd,’:k’);
>>fplot(‘x^2+4*sin(2*x)-1’,[-3 3]);
>>fplot(‘tanh’,[-2,2]) % plots y=tanh(x) over [-2,2]
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 17
MTH-331 Numerical Analysis Lab 2
Practice 23
Examples: plot of function y=3x3-26x+10, and its first and second derivatives for -2<=x<=4
>>x=[-2:0.01:4];
>>y=3*x.^3-26*x+6;
>>yd=9*x.^2-26;
>>ydd=18*x;
>>plot(x,y,’-b’);
>>hold on
>>plot(x,yd,’—r’);
>>plot(x,ydd,’:k’);
>>hold off
line(x,y,’PropertyName’,PropertyValue)
The line is almost same as plot except the line specifier, but the line style, color and marker
can be specified as property name and property value features.
Practice 24
Examples: plot of function y=3x3-26x+10, and its first and second derivatives for -2<=x<=4
>>x=[-2:0.01:4];
>>y=3*x.^3-26*x+6;
>>yd=9*x.^2-26;
>>ydd=18*x;
>>plot(x,y,’LineStyle’,’-‘,’color’,’b’);
>>line(x,yd,’LineStyle’,’--’,’color’,’r’);
>>line(x,ydd,’LineStyle’,’:’,’color’,’k’);
%Example Plot x and y on graph using linspace
>>x=linspace(0,1); % Row vector with 100 points
>>y=x.^n.*exp(x); % Gives row vector
>>plot(x,y,‘o') %or >>plot(x, x.^n.*exp(x))
%Example Plot ellipse c(t)=(2cos(t),3sin(t)), where 0<=t<=2pi
>>t=0:0.2:2*pi;
>>plot(2*cos(t),3*sin(t));
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 18
MTH-331 Numerical Analysis Lab 2
Formatting a Plot
The plot needs to be formatted to have a specific look and to display information in addition
to the graph itself i.e. axis labels, plot title, legend, grid, range of custom axis, and text labels.
Formatting can be done by using Commands and Editior
text(x,y,‘text as string’) %placed in the figure such that first character is at point x,y
gtext(‘text as string’) %placed in figure at position specified by the user with mouse
where pos is an optional number that specifies where the figure placed.
pos=-1 places the ouside the axes boundries on the right side
pos=0 places the inside the axes boundries in a location that less interfers with graph
pos=1 places the upper-right corner of the plot(default)
pos=2 places the upper-left corner of the plot
pos=3 places the lower-left corner of the plot
pos=4 places the lower-right corner of the plot.
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 19
MTH-331 Numerical Analysis Lab 2
Exercise 3
Create a 6 x6 matrix in which the middle two rows and the middle two columns are 1’s and the rest
are 0’s
Exercise 4
Using the eye command create the array A of order 7 x 7. Then using the colon to address the
elements in the array change the array as show bellow
2 2 2 0 5 5 5
2 2 2 0 5 5 5
3 3 3 0 5 5 5
A= 0 0 0 1 0 0 0
4 4 7 0 9 9 9
4 4 7 0 9 9 9
4 4 7 0 9 9 9
Exercise 5
Create a vector, name it Afirst, that has 16 equally spaced elements. First element is 4 and last
element is 49. Create a new vector, call it Asecond that has eight elements. The first four elements
are the first four elements of the vector Afirst, and the last four are the last four elements of the
vector Afirst.
Exercise 6
n
lim ⎛ 1⎞
Show that ⎜1 + ⎟ = e
n→∞ ⎝ n⎠
Do this by first creating a vector n that has the elements:1 10 100 500 1000 2000 4000
and 8000. Then create a new vector y in which each element is determined from the
n
⎛ 1⎞
elements of n by ⎜1 + ⎟
⎝ n⎠
Compare the elements of y with the value of e (type exp(1) to obtain the value of e).
Prepared By: FM Umar farooq and FM Kabeer Ahmed Page 20