Lecture-01 Basic Principles For Arrays and Plotting - MATLAB
Lecture-01 Basic Principles For Arrays and Plotting - MATLAB
1.1. Introduction.
In this textbook we introduce an introduction to the engineers programming
language (MATLAB), which makes you able to solve a lot of mathematical and
engineering problems such as solving of nonlinear equations, plotting a relation
between different sets of points, summation of series … etc.
1
5.0000 - 1.0000i
12.0000 + 2.0000i
Note that ( .' ) : means transpose of the array
and ( ' ) only: means conjugate transpose, which will transpose the array and
change all the imaginary part sign if it exists.
* Entering a matrix
>> m=[4 5 -2;0 9 -1;2 -7 1]
m=
4 5 -2
0 9 -1
2 -7 1
>> m=[4 5 -2;0 9 -1;2 -7 1];
Note that putting of semicolon at then end of the order makes the MATLAB not
to show the result of this order.
Vector generation: when the number of elements of the vector is
large and its elements form a series, it can be generated by either of
the following 2 orders
>> t=[0:2:10]
t=
0 2 4 6 8 10
>> t=[10:-2:0]
t=
10 8 6 4 2 0
OR
>> t=linspace(0,10,6)
t=
0 2 4 6 8 10
In the first order, we know the initial value, step and limiting value of the vector.
Where in the second order, we know the initial and final values and number of
elements in the vector
Step =(final value – initial value) / (No. of elements –1)
Special cases:
>> t=[0:6]
t=
0 1 2 3 4 5 6
when the step is not mentioned , it equals 1 by definition,
>> t=[0:2:7]
t=
0 2 4 6
it is not important to end by 7, but you must not exceed this value (7)
>> t=[0:0.01:15];
2
Without semicolon the page will be filled values because this vector contains
1501 values.
Matrix generation: the matrix can be generated as the vector by
generating each row or each column through the following
procedure.
>> A=[1:5;2:6;3:7]
A=
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
3
>> V(6)=21
V=
1 4 5 3 0 21 (we have defined a 6th element and the
MATLAB puts the 5th equal to zero)
>> V(2)=[]
V=
1 5 3 0 21 (we have eliminate the 2nd element)
>> A=[1 2;3 4];
>> A(1,3)=5
A=
1 2 5 (we have defined an element in 1st row and
3 4 0 3rd column)
>> A(3,5)=4
A=
1 2 5 0 0 (we have defined an element in 3rd row and
3 4 0 0 0 5th column , the MATLAB adds zeros as
0 0 0 0 4 shown to let each row having the same
number of elements)
1.4. Operations on arrays.
(I) Adding and subtracting : the addition and subtraction operation is the
simplest form of array operations.
We have two cases to be able to perform addition and subtraction.
(1) Adding or subtracting tow matrices of the same dimensions
>> A=[5 4 -2;1 2 -1;0 8 4];
>> B=[-1 -2 0; 2 0 4;-5 10 1];
>> C=A+B (will add each element in A to corresponding
C= element in B)
4 2 -2
3 2 3
-5 18 5
>> D=A-B (will subtract each element in B from corresponding
D= element of A)
6 6 -2
-1 2 -5
5 -2 3
(2) Adding or subtracting a scalar number to or from a matrix
>> X=[6 5 0;4 3 -1];
>> Y=X+5 (will add 5 to each element of X)
Y=
11 10 5
9 8 4
>> Z=X-1 (will subtract 1 from each element of X)
Z=
5 4 -1
3 2 -2
4
Properties of adding and subtracting:
A+(B+C) = (A+B)+C
A-(B+C) = A-B-C
A+B+C = B+C+A = C+A+B
5
(A * B) * C = A * (B * C)
A / B = A * inv (B)
A\B=B/A
A^2 = A * A
(A * B) Not equal to (B * A)
A*I=I*A=A (where I = identity matrix)
Special Matrices:
>> A=ones(3)
A= (square matrix 3*3 and all its elements are ones)
1 1 1
1 1 1
1 1 1
>> B=ones(2,3) (matrix 2*3 and all its elements are ones)
B=
1 1 1
1 1 1
>> C=zeros(2)
C= (square matrix 2*2 and all its elements are zeros)
0 0
0 0
>> D=zeros(2,3) (matrix 2*3 and all its elements are zeros)
D=
0 0 0
0 0 0
>> E=eye(4) (identity matrix 4*4 )
E=
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
>> x=[5 7 4];
>> F= diag(x) (diagonal matrix which is a square matrix and all its
F= elements are zeros except elements F11, F22, …, Fnn)
5 0 0
0 7 0
0 0 4
>> F= diag(1:3)
F=
1 0 0
0 2 0
0 0 3
(IV) Element by element operations: the element by element operation is a
good applications to multiply or divide two arrays element by
element, the simplest application of that operation that you have a
6
group of voltage values and corresponding current values and you
want to get the instantaneous power values.
>> V=[0 1 2 5 4 3 0 -1 -2 -5 -4];
>> I=[-0.1 0.2 0.4 0.6 0.4 0.2 0 -0.2 -0.4 -0.65 -0.5];
>> P=V.*I
P=
Columns 1 through 7
0 0.2000 0.8000 3.0000 1.6000 0.6000 0
Columns 8 through 11
0.2000 0.8000 3.2500 2.0000
The condition for element by element (multiplication or division or
exponentiation) is that the same dimensions of the two arrays you make
operation upon.
V.*I Element by element multiplication.
V./I Element by element left division.
V.\I Element by element right division.
V.^2 Element by element squaring.
V.^3 Element by element cubing.
V and I must have the same dimensions.
>> A=[1 0 2];
>> B=[0 0 5];
>> A.*B
ans =
0 0 10
>> A./B
Warning: Divide by zero.
ans =
Inf NaN 0.4000
>> A.^2
ans =
1 0 4
>> A.^3
ans =
1 0 8
>> 2.^A
ans =
2 1 4 = 21 20 22
>> exp(A)
ans =
2.7183 1.0000 7.3891 = e1 e0 e2
Important note : NAN = Not A Number = 0 / 0
Inf = Infinity = Any number / 0
7
1.5. Internal functions of the MATLAB.
It is important now to define the most commonly used functions in the
MATLAB.
Function Operation
Trigonometric and Hyperbolic functions
sin & cos & tan Calculate the trigonometric values of a radian angle
& cot & sec & >> A=sin(1.34)
csc A = 0.9735 (Note that the angle must be radian angle)
asin & acos & They are the inverse trigonometric function
atan & acot & >> A=acos(0.5) (A=cos-1 0.5)
asec & acsc A =1.0472 (This is a radian angle)
sinh & cosh &
tanh & coth & Calculate the Hyperbolic values of a certain value
sech & csch
Other functions
exp Exponential function
Log ' log10 Logarithmic function
sum Calculate the summation of a group of values
mean Calculate the average value of a group of values
max Determine the maximum value of a many values
min Determine the minimum value of a many values
abs Calculate the magnitude of each element in a matrix
angle Calculate the angle of each element in a matrix
real Calculate the real part of each element in a matrix
imag Calculate the imaginary part of each element in a matrix
conj Determine the conjugate of each element in the matrix
ones Create a matrix, all elements in it are ones
zeros Create a matrix, all elements in it are zeros
eye Create an identity matrix
diag Create a diagonal matrix
Create a vector knowing its begin, end and no. of
linspace
elements
length Calculate the number of elements in a vector
size Calculate the number of rows and columns in a matrix
inv Calculate the inverse of a square matrix
det Calculate the determinant
sqrt Calculate the square root of each value in a matrix
conv Multiply two polynomials
deconv Divide two polynomials
roots Calculate the roots of a polynomial
poly Determine the polynomial of known roots
polyder Calculate the derivative of a polynomial
polyval Determine the polynomial at certain values
polyfit Interpolate two groups of points in a form of polynomial
8
pi The constant value pi = 3.142857
eps Very small value eps = 2.22*10-16
For vectors ,
(Sum) : calculate the summation of all elements.
(mean): calculate the average value of all elements.
(max) : calculate the maximum value of the vector
(min) : calculate the minimum value of the vector
For Matrices ,
(Sum) : calculate the summation of each column and create a vector of
these values.
(mean): calculate the average value of each column and create a vector of
these values.
(max) : calculate the maximum of each column and create a vector of these
values.
(min) : calculate the minimum value of each column and create a vector of
these values.
Example (1)
>> X=[5 4 0 6 -1];
>> n=length(X)
n=
5
>> sum(X)
ans = (sum = 5 + 4 + 0 + 6 + (-1))
14
>> mean(X) (mean = sum / n)
ans =
2.8000
>> max(X)
ans =
6
>> min(X)
ans =
-1
>> [x,k]=max(X) (1st variable gives the maximum value and the 2nd gives
its
x= index )
6
k=
4
>> [x,k]=min(X) (1st variable gives the minimum value and the 2nd gives its
x= index)
-1
k=
5
9
Example (2)
>> Y=[4 5 0;2 1 -1;0 3 4]
Y=
4 5 0
2 1 -1
0 3 4
>> n=size(Y)
n=
3 3
>> sum(Y) (sum = [4+2+0 5+1+3 0-1+4])
ans =
6 9 3
>> mean(Y) (mean = sum / number of rows)
ans =
2 3 1
>> max(Y)
ans =
4 5 4
>> min(Y)
ans =
0 1 -1
>> [y,k]=max(Y) (1st variable gives the maximum value of each column
and
y= the 2nd gives their indices)
4 5 4
k=
1 1 3
>> [y,k]=min(Y) (1st variable gives the minimum value of each column and
y= the 2nd gives their indices)
0 1 -1
k=
3 2 2
Example (3)
>> A=[1+1i 2;3i 2-1i]
A=
1.0000 + 1.0000i 2.0000
0 + 3.0000i 2.0000 - 1.0000i
>> abs(A)
ans =
1.4142 2.0000
3.0000 2.2361
>> angle(A)
ans =
0.7854 0
1.5708 -0.4636
10
>> real(A)
ans =
1 2
0 2
>> imag(A)
ans =
1 0
3 -1
>> conj(A)
ans =
1.0000 – 1.0000i 2.0000
0 – 3.0000i 2.0000 + 1.0000i
Example (4)
>> A=[4 5 7 0];
>> n=length(A)
n=
4
>> s=size(A)
s=
1 4
>> B=sqrt(A)
B=
2.0000 2.2361 2.6458 0
>> C=exp(B)
C=
7.3891 9.3565 14.0940 1.0000
Note: How many decimal numbers appears?
>> s=4.2501364
s = 4.2501
>> format long (display 14 decimal numbers)
>> s
s = 4.25013640000000
>> format short (display 4 decimal numbers)
>> s
s = 4.2501
>> format bank (fixes the numbers to two decimal numbers )
>> s
s = 4.25
1.6. Polynomials.
The polynomials are the functions in the following form
F(x) = ao.xn + a1.xn-1 + a2.xn-2 + …. + an-1.x+ an
The polynomial is described in the MATLAB by a vector containing the
coefficients of powers of x.
11
To describe the equations. A(x) = 2 x3 + 5x2 – x + 4
B(x) = 5 x2 +1
2
C(x) = 2 x + 10 x - 5
>> A=[2 5 -1 4];
>> B=[5 0 1];
>> C=[2 10 -5];
The MATLAB deals with these vectors as polynomials, if we use with them the
polynomials orders (poly, roots, polyval, polyder, conv, deconv and trapz)
* Polynomial multiplication and long division:
M = conv (A,B) = A(x) * B(x).
[D,R] = deconv (A,B)
D = A(x) / B(x) , R = division remainder.
12
B=
44
>> B=polyval(A,[1,5]) (polynomial value at 1 , 5)
B=
11 527
>> B=polyval(A,[1:4]) (polynomial value at 1 , 2 , 3 , 4 )
B=
11 44 125 278
>> R=roots(A) (solve the polynomials and get the roots)
R=
0.1810 + 1.1612i
0.1810 - 1.1612i
-0.3620
>> C=poly(R) (find the polynomial of the given roots )
C=
1.0000 -0.0000 1.2500 0.5000
Note that: C is the same as A but all coefficient are divided by 4 to set the
greatest coefficient equal to unity
* Trapezoidal integration:
>> x=[0:4]
x=
0 1 2 3 4
>> y=[1 3 7 13 21]
y=
1 3 7 13 21
>> area=trapz(x,y)
area =
34
The MATLAB takes the xy points and join them by straight line then calculate
the area under the curve.
If the step in the x vector is small like x=[0:0.01:4]; , the calculated area will tend
to the exact value of integration.
Area 4
Area 3
Area 2
y Area 1
x
Trapz = Area 1 + Area 2 + Area 3 + Area 4 = Total Area
13
PROBLEMS
(1) Write down the output appeared on the command window when performing
the following orders.
>>s=[10:-2:0],
>>s1=s.^2
>>y=[1 2 3;4 5 6;7 8 9],
>>z1=sum(y) , z2=sum(s)
>>z=mean(z2)*mean(z1)
>>a=100*sin(30*s*pi/180)
>>c=max(size(s))
>>b=[1:c]
(2) Write down the output appeared on the command window when performing
the following orders.
>>a=[1:0.5:3]
>>b=[3:-0.5:1];
>>c=[a;b]
>>int=trapz(a,b)
>>x=a
>>x(3)=[],xs=sum(x)
>>y=b
>>y(3)=[],ya=mean(x)
>>Ab=xs*ya*a
>>Ac=xs*ya*int
(3) Write down the output appeared on the command window when performing
the following orders.
>>t=[0:4]
>>y=t+4*t.^2-5
>>p=polyfit(t,y,3)
>>y1=polyval(p,[1.2,1.5])
>>pd=polyder(p)
>>a=trapz(t,y)
(4) The following table shows the temperature in Cairo through one week
14
Use the MATLAB orders to get the maximum temperature and what is the number of
the day at which the temperate is maximum, and also get the minimum temperature
and the number of day at which the temperature in minimum.
1 2 3 4 5
R (Ohms) 104 2 * 104 3.5*104 105 2 * 105
V (Volts) 120 80 110 200 350
(7) Table (1) shows the costs associated with a certain product and table (2) shows the
production volume for the four quarters of the business year . Use MATLAB to
(a) Find the quarterly costs for material, labor and transportation.
(b) The total material, labor and transportation costs for the year
(c) The total quarterly costs
15
Chapter Two
Graph Plotting
2.1. Two dimensional plots
2.1.1 xy plotting functions
The most common plot is the xy plot. Its name assumes that we are plotting a
function y = f(x), although, of course other symbols can be used. We plot the x
values in the horizontal axis and the values in the vertical axis. MATLAB has
many functions and commands to produce various plots with special features.
Requirements for correct plots:
The following list describes the essential features of any plot.
(1) Each axis must be labeled with the name of the quantity being plotted
and its units
(2) Each axis should have regularly spaced tick marks at convenient
intervals – not too sparse, but not too dense with a spacing that is easy
to interpret and interpolate, for example use 0.1, 0.2, 0.3 ……
(3) If you are plotting more than one curve, label each on its plot or use a
legend to distinguish them.
(4) If you are plotting measured data, plot each data unit with a symbol
such as a circle, a square or cross.
(5) Sometimes data symbols are connected by lines to help the viewer to
visualize the data.
(6) Use a title to describe the whole plot.
>> x=[0:0.01:52];
>> y=0.4*sqrt(1.8*x);
>> plot(x,y)
>> xlabel('Distance (miles)')
>> ylabel('Hight (miles)')
>> title('Rocket hight as a function of downrange distance')
Title
ylabel
Tick
Mark
we have changed the limits of x and y axis but the MATLAB still selects the tick
marks.
Controlling tick marks spacing and labels:
The basic syntax is >> set(gca,'xtick',[0:4:52],'ytick',[0:5])
2
We have determined the spacing of ticks on the horizontal and vertical axis.
Note that; gca = get current axes, which means that this order saves axes
properties.
Example:
>> x=[1:6];
>> y=[13 5 7 14 10 12];
>> plot(x,y),grid
>> axis([1 6 0 15])
>> set(gca,'xtick',[1:6])
>> set(gca,'xticklabel',['Jan';'Feb';'Mar';'Apr';'May';'Jun'])
>> xlabel('Month'),ylabel('Monthly sales')
>> title('Printer sales for January to June 2003')
3
This equivalent to the following procedure
>> x=[1:0.01:2];
>> y=cos(tan(x))-tan(sin(x));
>> plot(x,y)
Compare the two figures, you will find that the function plot order is more
accurate or you need to introduce the vector x with lower value of step than 0.01
4
2.1.4 stem, stairs and bar plots:
MATLAB has several other plot types that are related to xy plots, these include the
stem, stairs and bar plots. Their syntax is very simple as shown in the following
example.
>> x=[1:6];
>> y=[25 18 13 22 15 24];
>> stem(x,y)
>> x=[1:6];
>> y=[25 18 13 22 15 24];
>> stairs(x,y)
>> x=[1:6];
>> y=[25 18 13 22 15 24];
>> bar(x,y)
5
2.2. Subplots
MATLAB can create figures that contain an array of plots, called subplot. These
are useful when you want compare the same data plotted with different axis types.
You can use the subplot command to obtain several smaller ‘subplots’ in the same
figure. The syntax is >> subplot(m,n,p). this command divides the figure window
into an array of rectangular windows with m rows and n columns, the variable p
tells the MATLAB to place the output of the plot command following to the
subplot number p
Example:
Plot the two functions y = exp (-1.2x) sin(10x + 5) for values of x from 0 to 5
and y = | x3 – 100 | for values of x from –6 to 6
>> x=[0:0.01:5];
Subplot Subplot
>> y=exp(-1.2*x).*sin(10*x+5); 1 2
>> subplot(1,2,1)
>> plot(x,y),xlabel('x axis'),ylabel('y axis')
>> x=[-6:0.01:6];
Subplot Subplot
>> y=abs(x.^3-100); 3 4
>> subplot(1,2,2)
>> plot(x,y),xlabel('x axis'),ylabel('y axis')
Subplot Subplot
5 6
Note that; if you want to modify anything in one plot, you must select its place
first by the order subplot(m,n,p), then you can make your modifications
6
>> plot(x,y,'g*') type of points: * color of points: green
>> plot(x,y,'r+') type of points: + color of points: red
>> plot(x,y,'r*') type of points: * color of points: red
>> plot(x,y,'b--') type of line: ---- color of points: blue
>> plot(x,y,'y:') type of line: ….. color of points: yellow
>> plot(x,y) default type of line: solid line
default type of points: Dot
Note: if you determine the type of points, the MATLAB doesn’t connect them by a
line, but you can connect them as follow.
>> plot(x,y,'g+',x,y, '--') it will plot two curves (one of them is y versus x with +
points, the other is the same xy curve connected with dashed line)
the following table shows the different types of data marks, line types and colors
>> x=[0:4];
>> y=x.^2+x+1;
>> z=-x.^2+4*x-1;
>> plot(x,y,'ro',x,z,'k--');
>> legend('y','z')
7
>> plot(x,y,'ro',x,y,'-',x,z,'k--');
Note that we have plotted more than one curve in the same figure, same result can
be obtained by using the hold order
>> plot(x,y,'ro');
>> hold,plot(x,z,'k--')
Current plot held
Example:
>> x=[0:0.01:1.5];
>> y1=2./sqrt(x);
Warning: Divide by zero.
8
>> y2=10.^(1-x);
>> subplot(2,2,1)
>> plot(x,y1,x,y2,'--')
>> subplot(2,2,2)
>> semilogy(x,y1,x,y2,'--')
>> subplot(2,2,3)
>> semilogx(x,y1,x,y2,'--')
>> axis([0 1.5 0 20])
>> subplot(2,2,4)
>> loglog(x,y1,x,y2,'--')
>> axis([0 1.5 0 20])
You can see that it is easy to just plot the curve you want and control all its
features inside the figure properties, not from the command window orders.
This makes easier dealing with plotting.
9
PROBLEMS
(1) The following functions describe the oscillations in electrical circuits and
the vibrations of machines and structures. Plot these functions on the
same plot. Because they are similar, decide how best to plot and label
them to avoid confusion.
x (t) = 10 e-0.5 t sin (3t + 2)
y (t) = 7 e-0.4 t cos (5t – 3)
(2) The following table shows the average temperature for each year in a
certain city. Plot the data as a stem plot, a bar plot and a stairs plot.
Year 1990 1991 1992 1993 1994
Temp. 18 19 21 17 20
(3) Use the hold command and the plot command twice to plot
y = sin (x) and y = x – x3 / 3
On the same plot for x changes from 0 to 1, use different types of lines and do all
the available plotting features (labels, title, legend, text,……)
(4) Pick a suitable spacing of t and v and use the subplot command to plot the first
function z = e-0.5t cos (20 t – 6) for t changes from 0 to 8 and the second function
u = 6 log10 (v2 + 20) for v changes from –8 to 8. Label each axis.
10