Beruflich Dokumente
Kultur Dokumente
discussions, stats, and author profiles for this publication at: https://www.researchgate.net/publication/288824058
CITATIONS READS
0 3,793
1 author:
SEE PROFILE
Some of the authors of this publication are also working on these related projects:
All content following this page was uploaded by Abdullah Ali Alshehri on 30 December 2015.
MATLAB for
Engineering
Applications
FIRST EDITION
4.1 Introduction
4.2 Matrices and Vectors in MATLAB
4.3 Solving Systems of Linear Equations
4.4 Special Functions and Applications
4.5 Inverse of Matrix
4.6 Determinants
4.7 Left-Division Method
4.8 Gauss Elimination Method
4.9 LU Decomposition Method
4.10 Vectors
4.11 Real Vector Spaces
4.12 Matrix and Eigenvalue Problem
4.13 Coding and Decoding
4.14 Summary List of Special Characters and MATLAB Functions
5.1 Introduction
5.2 Regression and Data Fitting
5.3 Interpolation
5.4 Non-Linear Solution Methods
5.5 Ordinary Differential Equations
6.1 Introduction
6.2 Fourier Transform
6.3 Z-Transform
6.4 Discrete Fourier Transform
6.5 Fast Fourier Transform FFT
6.6 Laplace Transform
7.1 Introduction
7.2 Ohm's Law
7.3 AC Circuits
7.4 Thevenins Theorem:
7.5 Maximum Power Transfer Theorem
7.6 Nodal Analysis Example
7.7 KVL and KCL Analysis
7.8 Mesh Current Analysis
9.1 Introduction
9.2 Train Systems
9.3 Modeling Cruise Control Systems
9.4 DC Motor Speed Modeling
9.5 Chemical Engineering Applications
10.1 Introduction
10.2 Waveforms Generations
10.3 Filters Implementations
10.4 Fourier Transform
10.5 Inverse Fourier Transform
10.6 Time-frequency Analysis
10.7 Spread Spectrum Communication Systems
10.8 Wireless Communications
10.9 Multipath Channel Modeling
10.10 Wavelet Transform
10.11 Artificial Neural Network
References
Preface
The ultimate goal of this book is to provide the reader with the fundamental skills and
knowledge required to use MATLAB for the simulation of engineering systems in a very
practical approach supported by exercises and real applications. It is intended for users
(engineers, applied engineers, mathematicians, etc.) who are running a professional
version of MATLAB and have basic understanding of math, linear algebra and numerical
analysis. The book assumes no prior knowledge of MATLAB and its applications in the
field of engineering and applied mathematics and numerical analysis. We believe that the
contents of this book will provide readers with the necessary knowledge and practical
skills to use MATLAB in the simulation and testing of algorithms for different problems
in the fields of applied science, engineering, and mathematics.
The book introduces the layout of MATLAB and its environment as an important
introductory step. Then we describe the concepts and fundamental functions of
MATLAB, using algebraic and arithmetic operations as a basis for its application. We try
to show the reader the power of MATLAB and how to simulate and write functions from
different engineering and applied math contexts and to produce illustrative results with
different formats. In later chapters the reader learns how to simulate mathematical
transformation methods such as Laplace, Fourier, and Z-transformations in MATLAB
using real engineering applications. These engineering applications include control
systems, communications, signal processing, mechanical, chemical, and electric circuit
analysis.
Acknowledgments
This book was funded by the Deanship of Scientific Research (DSR), King Abdulaziz
University, Jeddah, grant no.(421\829\1433). The author would hereby like to
acknowledge with thanks DSR technical and financial support.
The author would also like to extend his gratitude to Dr Yousef S. Mobarak for his
contribution to Chapter 8, and Engineer Nizamudheen for his assistance with data
collection, editing and preparing the Simulink tutorial in the Appendix.
PART I
Fundamentals of
MATLAB
Chapter 1
Introduction to MATLAB
Topics in this chapter include using the Command Window to perform arithmetical
operations, using numbers, plotting graphs, writing long command lines, interrupting a
running program, saving, reloading, using help, demos, and printing results in
MATLAB.
MATLAB is acknowledged as the leading numerical computing environment and
programming language for engineering and applied mathematics. It allows easy matrix
manipulation, implementation of algorithms, creation of data, and plotting of functions
and graphical results. Furthermore, users can easily interface MATLAB with programs in
other languages. The MATLAB Simulink platform adds model-based design and
graphical multidomain simulation for dynamic and embedded systems. MathWorks
claims that MATLAB is used by millions of people throughout industry and the academic
world.
Before we consider MATLAB tools and techniques, it is important to give a brief
summary of what MATLAB is and how it started. MATLAB derives from the "matrix
laboratory" invented in the late 1970s by Cleve Moler, a professor at the University of
New Mexico. It soon spread to other colleges and universities in the USA and found a
strong audience within the community of applied engineering and mathematics. Its
commercial potential was recognized by control engineer Jack Little in 1983 during
Moler's visit to Stanford University. He joined Moler and Steve Bangert and started to
rewrite MATLAB in C. In 1984 they founded MathWorks to continue its development.
Control design engineers were the first to adopt MATLAB but it quickly spread to many
other engineering fields such as mechanical, civil, chemical, communication, and image
and signal processing. It is now used in finance and applied mathematics for teaching
linear algebra and numerical analysis.
Later versions of MATLAB come with a graphical interface which makes working with
MATLAB more attractive than before. To start MATLAB double click on the MATLAB
icon from the desktop. The graphical user interface (GUI) which comes with MATLAB
is important and we recommend the reader to take a look at it before beginning work.
Figure 1.1 shows MATLAB's graphical user interface, which contains the command
window and bar menu. The graphical interface provides users with all the abilities
required for all functions as they make the appropriate selection: debugging, saving,
printing, sorting, graphing, editing, importing, exporting, etc.
Figure 1.1: MATLAB graphical user interface
MATLAB Command Window is the place where commands are interred. It allows the
user to clear all interred commands using the clc command.
To quit MATLAB and leave the current session type quit or exit at the prompt.
1.2 Variables
Variable names comprise characters including letters and numbers. For any expression a
variable name must be given otherwise the variable ans will be given as the variable
name.
For simple computations the user needs to type the command first followed by the Enter
key
s = 1 + 5
s =
6
ross = cos(pi/4)
ross =
0.7071
where the trigonometric function cosine and the constant pi are used.
The results of the previous computations are automatically saved in variables with their
names. To recall them during a current MATLAB session, the user should type their
names followed by the Enter key,
s
s = 6
ross
ross = 0.7071
The variable ans will be assigned if no variable name has been specified. For example,
100/cos(pi/3)
result in
ans = 200.000
The short format is the default one in MATLAB. For this format, four digits are
displayed after the decimal point. To display a different format, the user clicks on File,
then selects Preference, and from the list selects the desired format required before
clicking on Apply followed by OK. Different formats can be selected. For example,
format long
changes current format to long format.
The result is that more digits will be displayed
ross
ross =
0.70710678118655
format short
ross
ross =
0.7071
To close MATLAB session type exit or quit on the command window and then press
Enter key. Another way of exiting MATLAB is by selecting File from the toolbar and
clicking on Exit MATLAB. It should be borne in mind that all unsaved data residing in
the MATLAB Workspace will be lost.
real numbers
integers
complex numbers
xi = 20
xi =
20
xr = 20.01
xr =
20.0100
As regards the smallest and largest positive numbers, the variables realmin and realmax
denote them respectively. For example,
realmin
ans =
2.2251e-308
The rectangular form is the only way to represent complex numbers in MATLAB. The
imaginary unit is usually denoted by the letters j or i where j or i=sqrt(-1)
i
ans =
0 + 1.0000i
Table 1.2 shows a list of complex functions used in MATLAB with descriptions of the
conversion between polar and rectangular forms.
In addition, three distinct variables are used in MATLAB to represent the non-numbers
-Inf
Inf
NaN
-Inf and Inf variables are representations of positive and negative infinity as defined by
IEEE. Infinity is obtained by dividing by zero or at the overflow. NaN denotes a not-a-
number obtained from undefined operations.
c=Happy
c=
Happy
Cs=[c,Smile]
Cs =
Happy Smile
1.6 Functions
Fortunately, most of the standard functions are included in MATLAB and have a separate
code. These functions include sin, cos, log, exp, sqrt, and many others. For example,
cos(pi/4)
ans =
0.7071
Note that there are two operators for division each with different function
rd = 20/3
rd =
6.6667
ld = 20\3
ld =
0.1500
will give
a =
1 3 5 8 1 5 4 2 2
Let us create a short vector with elements evenly spaced with increments of three
between zero and 12:
s = 0:3:12
s =
0 3 6 9 12
b = a + 3
b =
4 6 8 11 4 8 7 5 5
A=[1; 2; 3; 4]
A=
1
2
3
4
B=zeros(1,5)
B=
0 0 0 00
Z=ones(1,5)
Z=
1 1 1 1 1
c = a + b
c =
5 9 13 19 5 13 11 7 7
x =
1 3 -15 -2 9
A vector of length n+1 can be interpreted in MATLAB as an nth order polynomial. One
needs to inter zeros for any missing coefficients. For example,
y x4 1
is represented in MATLAB as
y = [1 0 0 0 1]
The function polyval can be used to find the value of the polynomial.
Let us try to find the polynomial of the above equation using the polyval function at
s=2
p = polyval([1 0 0 0 1],2)
p =
17
The polynomial roots can be extracted using the command roots. Consider again the
high-order polynomial
When two polynomials are multiplied together, the product is simply the convolution of
their coefficients. The function conv from MATLAB will solve it
r = [1 2];
s = [1 4 8];
x = conv(x,y)
x =
1 6 16 16
We can use deconv function for dividing two polynomials. It will return the result and
the remainder. Now let us divide x by s and see if we get r
[xx,R] = deconv(x,s)
xx =
1 2
R =
0 0 0 0
Matrices can be entered into MATLAB in a similar way to vectors. The rows of the
matrix are separated by a semicolon (;)
B =
2 2 3 4
7 7 9 8
2 1 11 12
C = B'
C =
2 7 2
2 7 1
3 9 11
4 8 12
For complex matrices use the command .' for transpose. The apostrophe gives the
complex conjugate transpose.. Note that if the matrix is not complex the two commands
are the same.
We can address any row or column in a matrix using the symbol (:).For example
R2=c(2,:)
R2 =
2 6 10
displays elements of the second column in C.
D = C * B
D =
57 53 91 88
53 51 77 72
91 77 211 216
88 72 216 224
The MATLAB operator .* is used when multiplying the corresponding elements of two
equal size matrices.
All matrices operations including summation, subtraction, division, and other operations
are performed in MATLAB in a direct and simple way. Suppose we have
X=A+B
X=
4 7 5
9 7 14
10 14 18
With a dot product we multiply the corresponding elements of two equally sized matrices
using the .* operator. For example
E = [1 2;3 4]
F = [2 3;4 5]
G = E .* F
E =
1 2
3 4
F =
2 3
4 5
G =
2 6
12 20
E^3
ans =
37 54
81 118
E.^3
ans =
1 8
27 64
X = inv(E)
X =
-2.0000 1.0000
1.5000 -0.5000
or its eigenvalues
eig(E)
ans =
-0.3723
5.3723
In MATLAB there is an important function named poly which is used to find the
coefficients of the characteristic polynomial of a matrix
pl = poly(E)
pl =
1.0000 -5.0000 -2.0000
Note that the eigenvalues of a matrix and the roots of its characteristic polynomial are the
same
roots(pl)
ans =
5.3723
-0.3723
Example 1.1
The linear system below is represented by the matrix equation Ax=B. It is required to
determine the vector x
4 - 2 - 10 x1 - 10
2 10 - 12 x 32
2
- 4 - 6 16 x3 16
Example 1.2
In order to compute the diagonal elements of any matrix we need to use the function diag.
ans =
1
1
1
1
1
Example 1.4
Mixed data numerics and text are written to the file named tempdata.xls
d = {'Time', 'Temp'; 12 98; 13 99; 14 97};
Now we call xlswrite, to specify the worksheet to write the data as labeled Temperatures
and a 4-by-2 matrix will be written
s = xlswrite('tempdata.xls', d, 'Temperatures', 'E1')
s=
1
shows that the write operation succeeded. Data will appear in the output file as
Time Temp
12 98
13 99
14 97
x =
0.7744
If we want to suppress output to the screen, we need to add a semicolon after the
statement
r = 3 + 4;
1.11 Demos
A demo command is provided in MATLAB to provide the user with additional learning.
It can be executed either from the Command Window or the Pull-down menu. From the
menu we just click on Help, then select Examples and Demos.
We can interrupt a running program simply by pressing the two keys Ctrl-c
simultaneously.
whos
Name Size Bytes Class
ans 1x1 16 double array (complex)
run 1x1 8 double array
ld 1x1 8 double array
rd 1x1 8 double array
To save the current workspace from the File menu select Save Workspace as and write a
name for the file in this format filename.mat, then click on Save. The created file must
be located in MATLAB's search path. It can also be saved directly from the Command
Window by typing save filename command and variables will be saved. To save
workspace we type the command diary filename and all created variables and commands
are saved in our file from this point. If we want to save it as a text file we need to use the
command diary off. To load a file into the workspace, we need to type the load filename
command.
help abs
ABS Absolute value.
ABS(X) is the absolute value of the elements of X. When X is complex, ABS(X) is
the complex modulus (magnitude) of the elements of X.
When we forget or do not exactly remember the full name of a function, then we can use
the command lookfor. For example
lookfor sqrt
REALSQRT Real square root.
SQRT Square root.
SQRTM Matrix square root.
EML_FISQRT_HELPER Helper function for eml-fixedpoint square
root
vsqrtm.m: % function out = vsqrtm(mat)
REALSQRT Overloaded for distributed arrays
SQRT Overloaded for distributed arrays
SQRTM Matrix square root.
SQRTM Matrix square root.
SQRT Symbolic matrix element-wise square root.
In order to open a new window on the screen, we need to use helpwin command. To
display the help text file for any function of command we double click on the
subdirectory, then double click on the selected function or command. A direct way to get
help text is with using helpwin command followed by an argument.
1.15 Printing
MATLAB provides the user with easy functions and commands to print. The steps
needed for popular operation systems are as follows.
Click on M-file or the plot, then select Print from the File menu and hit return.
Unix
For Unix workstation we need to enter the command print -
P<printername>. To save a plot, we need to enter the command print
plot.ps or use the command lpr -P plot.ps. For an HP workstation,
we would instead use the command lpr -d plot.ps. To print an M-file, use
the command lpr -P <name of m-file>.m. For an HP workstation, we
would instead use the command lpr -d plot.ps<name of m-file>.m.
Exercises
3. Evaluate manually the given expressions, then use MATLAB to check the
answers:
(a) 2 / 2 * 3 (b) 2 / 3 2 (c) (2 / 3) 2
(d) 2 + 3 * 4 4 (e) 2 2 * 3 / 4 + 3 (f) 2 (2 * 3) / (4 + 3)
(g) 2 * 3 + 4 (h) 2 3 2 (i) 4 2
6. For matrix B, find the array which results from the operation [B; B']. Use
MATLAB to determine which number is in row 5, column 3 of the result:
7. For the same matrix B, use MATLAB to (a) find the largest and smallest element
in B and their indices and (b) sort each column in B to create a new matrix C.
9. Find their (a) array product, (b) array right division (A divided by B), and (c) B
raised to the third power element by element.
>> x=(1:2:5)
>> A=[x,x.^2,x.^3]
12. The MATLAB library stores data files and helps the user by loading and
displaying them. Load the files handle and earth using load command. Now we
need to know about these two files. Play the handle file using sound command.
We now need to have a speaker. For the earth file we will use the image
command to show the contents. When we have finished with them we may try
loading chirp, gong, laughter, splat, and train. These are audio files and therefore
we must use a sound command.
13. Generate a magic matrix using MATLAB command magic(k) which will generate
a
square magic matrix of KxK elements. Use the sum command to verify that the
sum of all
elements in each row, column, and diagonal of the created matrix has the same
value.
Chapter 2
MATLAB Graphics
2.1 Graphics
Creating plots in MATLAB is an easy process. The matrix and vector outputs which can
be obtained from MATLAB offer more flexibility for plotting in attractable and readable
graphs. Suppose we want to plot a function that varies with time. We first make a time
vector and then compute the function at each time element of the given vector, as
described in the next example.
Example 2.1
In this example we will show how one can generate a MATLAB graphical output using
the provided tools and features. The following script file explains how to generate sine
and cosine functions and display their output plots.
0.8 0.8
0.6 0.6
0.4 0.4
0.2 0.2
Amplitude
0 0
-0.2 -0.2
-0.4 -0.4
-0.6 -0.6
-0.8 -0.8
-1 -1
0 2 4 6 8 0 2 4 6 8
Time samples Time samples
As stated in the above script file the output should generate two different plots. The plot
shown on the left of Figure 2.1 displays the sine waveform for one period of time and that
on the right the cosine waveform for one period of time. The script file also explains how
to plot multiple functions in one graph using the subplot command.
0.6
0.4
0.2
Amplitude
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
Time samples
Figure 2.2 contains both the sine and cosine waveforms in a single graph. We have used
just some of the capabilities which MATLAB has. As can be seen, both y and x axes were
labeled and the background of the graph was gridded using the grid command. Because
we have two plots in one graph, the legend function was also used.
The syntax for plots includes the following optional symbols and colors (Table 2.1).
Table 2.1 Color specifications and line style options
Color Specification Line style option
Long name short name Style Symbol
White w Plus +
Black k Solid _
Green g Dash-dot -.
Cyan c Dotted :
Blue b Dashed --
Red r Circle o
Magenta m Point .
Yellow y Star *
Example 2.2
From the script file above we get four different plots, as shown in Figure 2.3. Note that in
the last figure we show how to use the subplot command for combining more graph plots
together in one universal graph.
4
1500 10
2
1000 10
y - Linear
y - Log
0
500 10
-2
0 10
0 20 40 60 0 20 40 60
x - Linear x - Linear
4
1500 10
2
1000 10
y - Linear
y - Log
0
500 10
-2
0 10
-2 0 2 -2 0 2
10 10 10 10 10 10
x - Log x - Log
Figure 2.3: Plots of the function y with linear, semilog, and loglog scales
2.3 Plots with Special Graphics
So far, all plots which have been introduced are of the line type where data points are
connected by lines. In some, practical representation of data is required for graphical
representation.
Example 2.3
Consider using the sales data from a computer company for its annual sales for a certain
period (1988 until 1994). With MATLAB, it is possible to plot these data in 2-D
different plot styles as shown in Figure 2.4. The script file is
Example 2.4
Consider grades distribution of a class as
Grade A B C D E
Number of Students 11 18 26 9 5
which gives the final pie chart in Figure 2.5 showing the distribution of class grades.
Class Grade
7% A
16%
B
C
13%
D
E
26%
38%
Figure 2.6 displays the different plotting formats for data used in example 2.4.
1-D Pie Plot 3-D Bar Plot
7%
16% 10
13%
5
26% 0
12
34
38% 56
7 3
1 2
42% 42%
10% 10%
19% 19%
29% 29%
Note that more elementary 3-D plots can be found by using the Help command.
2.6 Histograms
A histogram plot shows the distributions of data where the overall range of a given set of
data is divided into smaller subranges or bins and the histogram shows how many data
points are in each bin.
Example 2.5
Let us generate a random matrix measuring 60x60. The MATLAB script file is
y=randn(60); %generate 60x60 matrix of random data
y=y(1,:); %taking the first row to be our data subplot(121),
plot(y)
xlabel('data samples')
ylabel('Amplitude')
subplot(122)
hist(y)
3 12
2 10
Amplitude 1 8
0 6
-1 4
-2 2
-3 0
0 20 40 60 -4 -2 0 2 4
data samples
The random data of the first row and its histogram is shown in Figure 2.7.
Example 2.6
x
f ( x)
, -2 x 2
1 x2
which we need to plot with the elements of its vector representation [1].
% MATLAB solution
for n=1:2:5
n10 = 10*n;
x = linspace(-2,2,n10);
y = x./(1+x.^2);
plot(x,y,'r')
xlabel('x')
ylabel('y')
title('2-D Graph')
grid
pause(3)
end
Notice that several curves can be displayed in sequence, separated by three seconds, with
the pause command. The final curve is shown in Figure 2.8.
Example 2.7
t = 0:pi/100:2*pi;
x = cos(t);
y = sin(t); plot(x,y)
Figure 2.9: Unit circle of radius 1
w white
y yellow
r red
m magenta
g green
k black
b blue
c cyan
Example 2.8
A new function fill will be used in this example where we try to fill a well-known object
n = -6:6;
x = sin(n*pi/6);
y = cos(n*pi/6);
fill(x, y, 'c')
axis('square')
title('Graph of the n-gone')
text(-0.45,0,'Please turn off your computer?')
Three input arguments or parameters are adopted. Two arrays/vectors, x and y, are
selected and the third parameter is 'c' for the selected color. The new command text is
used to annotate a text. The first two inputs are used to specify the text location and the
third one is the added text. Figure 2.10 displays the generated graph of the filled object.
Example 2.9
[X,Y] = meshgrid(-8:.5:8);
K = sqrt(X.^2 + Y.^2) + eps;
Z = sin(K)./K;
mesh(X,Y,Z,'EdgeColor','blue')
Figure 2.11: Mesh plot of the sinc function
To create a transparent mesh we need to disable hidden lines by using the command
hidden off.
Example 2.10
Generating colored surface plots is similar to generating a mesh plot. The only difference
is that we color the rectangular faces of the surface using the colormap command.
surf(X,Y,Z)
colormap hsv
colorbar
Example 2.11
r(t) = t cos(t),
t sin(t), -20< t < 20,
The following script file [1] shows how to use the command function plot3 over a given time
interval
% Curve Function
t = -20*pi:pi/100:20*pi;
x = t.*cos(t);
y = t.*sin(t);
h = plot3(x,y,t);
set(h,'LineWidth',1.25)
title('Curve Function')
h = get(gca,'Title');
set(h,'FontSize',12)
xlabel('x')
h = get(gca,'xlabel');
set(h,'FontSize',12)
ylabel('y')
h = get(gca,'ylabel');
set(h,'FontSize',12)
zlabel('z')
h = get(gca,'zlabel');
set(h,'FontSize',12),grid
Note that the function plot3 was used with three inputs representing the three parameters
related to the coordinates of points on the plotted curve (Figure 2.13).
The mesh function is used to plot 3-D mesh surfaces where the function meshgrid
generates two-dimensional arrays used for 3-D plots.
One example of this function is when we want to plot a mesh surface in this form
x = [1 2 3];
y = [11 12 14];
Note that the matrices xi and yi contain replicated rows and columns of the arrays x and y
respectively.
2.7.4 Sphere and cylinder commands
For generating special surfaces in MATLAB some functions are used. We focus our
attention on the two most commonly used ones, sphere and cylinder.
We need to type the command sphere(n) in order to get a sphere centered at the origin.
If n is not specified, then the default valued n=20 is used. The center of the sphere can
be translated easily. The next example explains how to plot a unit sphere graph centered
at the coordinate points (2, -1, 1).
[x,y,z] = sphere(20);
surf(x+2, y-1, z+1)
title('Sphere')
To plot spheres of arbitrary radii, we need to use the function sphere together with the
surf or mesh function. Figure 2.14 displays the obtained sphere plot with surf function.
The function cylinder is usually used when we need to plot the surface of revolution by
taking two optional input arguments or parameters: for example, the command
cylinder(r, n), where r is the parameter/vector defining the cylinder radius on the z-axis
and n is a scalar specifying the number of points used to define the cylinder's
circumference. Figure
cylinder([1 0])
title('CONE')
Figure 2.15: Plot of cylinder
is a cone with unit diminution for both its base radius and its height.
It is possible to plot a graph of the surface and rotate the curve about the y-axis.
t = 0:pi/100:pi;
r = sin(t);
plot(r,t)
cylinder(r,15)
shading interp
3.5
2.5
1.5
0.5
0
0 0.2 0.4 0.6 0.8 1
0.8
0.6
0.4
0.2
0
1
0.5 1
0 0.5
0
-0.5 -0.5
-1 -1
2.7.5 Animation
Example 2.12
To create a movie object, consider the following MATLAB file in which we try to run a
sequence of graphs in motion or movie.
m = moviein(5);
x = 0:pi/100:pi;
for i=1:5
h1_line = plot(x,sin(i*x));
set(h1_line,'LineWidth',1.5,'Color','m')
grid
title('Sine functions sin(kx), k = 1, 2, 3, 4, 5')
h = get(gca,'Title');
set(h,'FontSize',12)
xlabel('x')
k = num2str(i);
if i > 1
s = strcat('sin(',k,'x)');
else
s = 'sin(x)';
end
ylabel(s)
h = get(gca,'ylabel');
set(h,'FontSize',12)
m(:,i) = getframe;
pause(2)
end
movie(m)
Five frames will be replayed again at a different speed.
The command moviein tells MATLAB to create five frames. The consecutive frames
will be generated inside the loop for where the command getframe is to store movie in
the matrix m. The last command movie(m) is to tell MATLAB to start playing a movie
of the created and stored frame/s in the matrix m.
To print graphs to an M-file we need to use the built-in device drivers. Any graph can be
printed to an M-file using any of the following built-in device drivers:
-depsc Level 1 color Encapsulated PostScript
-deps2 Level 2 black and white Encapsulated PostScript
-depsc2 Level 2 color Encapsulated PostScript
If, for example, we want to print a graph to an M-file with level 2 color Encapsulated
PostScript, we need to execute this command: print depsc2 figure name. This
command can either be put inside the M-file or executed from the Command Window.
Programming in MATLAB
This chapter will help users to learn the fundamental programming skills of MATLAB
language. Beginners will be able to write their computer codes for solving problems even
with limited knowledge of MATLAB language. Numerous examples are included to help
users quickly learn the basic tools and techniques of how to program in MATLAB.
Topics introduced in this chapter will include writing M-files, using relational and logical
operators, strings, inline functions, cell arrays, control flow, and MATLAB graphics.
In order to create an M-file we click on File, then select New and from the pull-down
menu select M-File. A MATLAB Editor screen will appear where we can write our
code. For saving your code, from File select Save As and then we can chose a name for
your file and click on Save. and It is important saved it a MATLAB's search directory.
Note that if there are more than one file with duplicated names, the first occurred in the
search path will be executed. For opening existed m-file from the command window we
need to type filename then press Enter key and the file will be displayed.
0.8
0.6
0.4
0.2
-0.2
-0.4
0 5 10 15 20 25 30 35
a=[4 6 -1 8];
[b,j]=sortdesc(a)
b=
8 6 4 -1
j=
4 2 1 3
Note that if we execute function sortdesc without output arguments we will lose the
permutation information
sortdesc(a)
ans =
20.0000 4.0000 0.1500 -10.0000
The output results will be assigned the default variable ans since there is no defined
output argument.
k = inline('sqrt(m.^2+n.^2)','m','n')
k=
Inline function:
k(m,f) = sqrt(m.^2+n.^2)
k(3,4)
ans =
5
and
Z = zeros(2)
Z=
0 0
0 0
Then
D = k(M, Z)
D=
3 4
5 6
for m = array
commands
end
All commands between the statements for and end will be executed for all values of the
array.
Example 3.1
In this example we want to obtain values of a cosine function at 20 evenly spaced points
t/10, for t = 0, .1, , 1 using for loop
for t=0:1:20
x(t+1) = cos(pi*t/20);
end
x
Columns 1 through 7
1.0000 0.9877 0.9511 0.8910 0.8090 0.7071 0.5878
Columns 8 through 14
0.4540 0.3090 0.1564 0.0000 -0.1564 -0.3090 -0.4540
Columns 15 through 21
-0.5878 -0.7071 -0.8090 -0.8910 -0.9511 -0.9877 -1.0000
This is an example of for loops where we repeat the process of the program once for each
index value i.
function z=add(r,c)
% This function adds two matrices a and b
%
[r,c]=size(a);
[k,l]=size(b);
if r~=k | c~=l,
r='ERROR: matrices are not the same size';
return,
end
z=zeros(r,c);
for i=1:r,
for j=1:c,
z(i,j)=a(i,j)+b(i,j);
end
end
Example 3.2 Matrices Multiplication
function z=mult(a,b)
% produces a product of the matrices a and b
%
[r,c]=size(a);
[k,l]=size(b);
if c~=k,
z='ERROR: matrices are not compatible for multiplication',
return,
end,
z=zeros(r,l);
for i=1:r,
for j=1:l,
for e=1:c,
z(i,j)=z(i,j)+a(i,e)*b(e,j);
end
end
end
We create the famous Hilbert matrix using for loops. Note this matrix can be nested and
has two levels of for loops
HM = zeros(7);
for r=1:7
for c=1:7
HM(r,c) = 1/(r+c-1);
end
end
HM
HM =
Similarly to before we start creating a row vector k of integers 1, 2, , 10. In the second
line we multiply the two vectors sin(r)' and cos(r) to get matrix A. This is what is called
vectorization in MATLAB and is a technique to be used whenever possible.
while expression
statements
end
Let us now try to solve a problem that requires the use of a while loop. We want to
divide the by two and the result is again divided by two until it is equal to or less
than 0.02. If it is necessary to know the largest quotient greater than 0.02, the while
loop is the right tool.
r = pi;
while r > 0.02
r = r/2;
end
r
r=
0.0123
Note that as long as the condition value is not zero, this program will execute
successfully.
The algorithm of the bisection method used to solve nonlinear functions is discussed in
Chapter 5. Let us look at the use of the while loop now, however.
% Bisection
m = 0; fm = -Inf;
n = 3; fn = Inf;
while n-m > eps*n
x = (m+n)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fm)
a = x; fm = fx;
else
n = x; fn = fx;
end
end
x =
2.0946
Continue: is a statement used to pass control to the next iteration of the for or while
loop and skips remaining statements in the body of the loop.
Example 3.6
snd = fopen('magic.m','r');
count = 0;
while ~feof(snd)
line = fgetl(snd);
if isempty(line) | strncmp(line,'%',1)
continue
end
count = count + 1;
end
disp(sprintf('%d lines',count));
In MATLAB, the comparison of quantities or arrays needs one of the special operators
shown in Table 3.2.
Note that the operator == is used to compare two given variables. It gives ones when the
two variables are equal and zeros otherwise. For example,
a = [1 1 3 4 1]
a=
11341
To compare a with 1
fin = (a == 1)
fin =
11001
b = a(fin)
b=
125
Instead of using logical operators, we can use the function find to obtain the same result
fin = find(a == 1)
fin =
125
3.3.5 Logical Operators
Logical operators are used in MATLAB programming. They are listed in Table 3.3.
Let us show how to use these operators. Suppose that we have the inequality t 1or t<-
0.5 and need to select entries which satisfy it.
t = randn(1,5);
t=
0.5377 1.8339 -2.2588 0.8622 0.3188
is an array of random numbers that is normally distributed.
y = t(ind)
y=
1.8339 -2.2588
MATLAB has several additional functions which perform similarly to the logical
operators. They return one when the condition is satisfied and zero otherwise. Their
names usually begin with the prefix is. For example,
isempty(y)
ans =
0
because the array y is not empty.
isempty([ ])
ans =
1
because the argument is empty [ ].
Let us try using the isempty command through the following function.
function df = derp(c)
% df is the derivative of the algebraic polynomial represented by
% polynomial coefficients c stored in descending order.
m = length(c) - 1;
c = c(:)'; % to make sure c is a row vector.
df = c(1:n).*(m:-1:1); % to apply Power Rule.
h = find(df ~= 0);
if ~isempty(h)
df = df(h(1):end); % remove any leading zeros
else
df = 0;
end
if expression
commands
end
and is used with only one alternative.
For several alternatives the following construction is used
if expression1
commands (evaluated if true )
elseif expression 2
commands (evaluated if is true)
elseif
.
.
else commands (executed if all expressions are false)
end
In the next numerical examples we will show how to implement these constructions in
different scenarios.
Example 3.7
Your bank offers an interest rate of 7% when the amount in your account is less than
$4200 and 10% otherwise. Your current balance is $10000. The MATLAB script for
implementing this statement is:
bal = 10000 ;
if bal < 4200
rate = 0.07;
else
rate = 0.10;
end
newbal = bal + rate * bal;
and will give the instantaneous final new balance (newbal); it does not consider the
period of time you want to keep your money for.
Example 3.8
Suppose that the bank in the last example offers interest rates as follows
Now, we have $4900 and want to invest it for 10 years. Write a MATLAB code to
compute the following.
What is your final balance?
Plot the balance growth using the correct plotting format.
16000
14000
12000
10000
$
8000
6000
4000
2000
0
1 2 3 4 5 6 7 8 9 10
Years
Switch command compares inputs with each case value and then executes once a match
is found.
Example 3.10
When we tried to run the above script file five times we got these results
P = 20%
P = 30%
P = 50%
P = 30%
P = 50%
3.4 Strings
Strings are an array of characters replaced in as their elements. Each character in the
array is represented by its ASCII value.
Example 3.11
mis1 = double(mis)
mis1 =
Columns 1 through 15
73 32 97 109 32 116 114 97 118 101 108 105 110 103 32
Columns 16 through 30
116 111 32 67 97 110 97 100 97 32 116 104 105 115 32
Columns 31 through 37
115 117 109 109 101 114 46
str2 = char(mis1)
str2 =
I am traveling to Canada this summer.
If we want to compare the two strings for equality we can use the function strcmp
strcat(mis,str2)
ans =
I am traveling to Canada this summer. I am traveling to Canada this summer.
3.5.2 Indexing
celldisp(A)
A{1} =
Ahmed Hussain
A{2} =
313125678
B(1) = []
B=
[1x9 double]
celldisp(C)
C{1}{1} =
Ahmed Hussain
C{1}{2} =
313125678
C{2}{1} =
313125678
T = randn(5)
T=
0.5377 -1.3077 -1.3499 -0.2050 0.6715
1.8339 -0.4336 3.0349 -0.1241 -1.2075
-2.2588 0.3426 0.7254 1.4897 0.7172
0.8622 3.5784 -0.0631 1.4090 1.6302
0.3188 2.7694 0.7147 1.4172 0.4889
A = floor(T)
A=
0 -2 -2 -1 0
1 -1 3 -1 -2
-3 0 0 1 0
0 3 -1 1 1
0 2 0 1 0
B = ceil(T)
B=
1 -1 -1 0 1
2 0 4 0 -1
-2 1 1 2 1
1 4 0 2 2
1 3 1 2 1
C = fix(T)
C=
0 -1 -1 0 0
1 0 3 0 -1
-2 0 0 1 0
0 3 0 1 1
0 2 0 1 0
D = round(T)
D=
0 -1 -1 0 0
1 0 3 0 -1
-2 0 0 1 0
0 3 0 1 1
0 2 0 1 0
Problems
3. Use MATLAB to compute the arithmetical mean shown in the equation below. First
create the vector g of a random real number with n=20.
1 n
mean( g ) gk
n k 1
PART II
4.1 Introduction
As mentioned in the first chapter all mathematical operations and algorithms can be
simulated in MATLAB. A distinct feature of MATLAB is its simplicity in terms of
performing computations using vectors and matrices. This chapter will explain how
matrices and vectors are used in MATLAB, including solving systems of linear
equations, determinants, inverse of an invertible square matrix, linear transformation,
eigenvalue problems and representing vectors in n-dimensional space. Linear numerical
methods such as regression, interpolation, roots of non-linear equations, special
functions, different types of series, curve fitting, message coding, and computer graphics
will be presented with some examples and applications.
x = [2 3 4]
x =
2 3 4
y = [2;3;4]
y =
2
3
4
For transpose and conjugate transpose we use conjugate transpose ' and quote operator
,' respectively. Let us create a vector x + i*y' and perform the following operations
(x+i*y')'
ans =
2.0000 - 2.0000i
3.0000 - 3.0000i
4.0000 - 4.0000i
while
(x+i*y').'
ans =
2.0000 + 2.0000i
3.0000 + 3.0000i
4.0000 + 4.0000i
length(x)
ans =
3
An example of using dot operator. is
x.*x
ans =
4 9 16
x.^2
ans =
4 9 16
To obtain wise division we use the backslash and dot operators .\ together,
x.\y'
ans =
1 1 1
outprod = x*y'
outprod =
4 6 8
6 9 12
8 12 16
In the case of a three-dimensional vector, we use the command cross. The cross-product
of the two vectors a and b is
a = [1 2 3]
b = [-2 1 2];
cp = cross(a,b)
cp =
1 -8 5
Now we need to deal with matriX operations such as addition, subtraction, and scalar
multiplication.
We can extract submatrix B from A with columns 1 and 2 and rows 1 and 3
B = A([1 3], [1 2])
B =
1 2
7 8
Note that the colon operator : is used when we want all rows or all columns.
A(:, 2) = []
A =
1 3
4 6
7 10
It is possible with MATLAB to extract entries to satisfy an imposed condition. Now let
us extract all entries greater than one in matrix A.
A = [-1 2 3;0 5 1]
A =
-1 2 3
0 5 1
A > 1
ans =
0 1 1
0 1 0
returns ones on the locations of entries with values greater than one.
A(A > 1)
ans =
2
5
3
The dot operator . can be used as
A = [1 2 3; 3 2 1] ;
A.*A
ans =
1 4 9
9 4 1
computes the element-by-element product of A with A.
The command diag can be used for different purposes. We can create a diagonal matrix
using the elements of vector d as the diagonal entries
d = [1 2 3];
D = diag(d)
D =
1 0 0
0 2 0
0 0 3
Furthermore, the diag command can be used to obtain the diagonal of a matrix
d = diag(D)
d =
1
2
3
a11 x1 a12 x 2 b1
a 21 x1 a 22 x2 b2
The solution of the system is obtained at x1=x2. To find their solution graphically, we
need to solve both equations for x2
a b
x 2 11 x1 1 x 2 (slope)x1 intercept
a12 a12
a b
x 2 21 x1 2
a 22 a 22
Now we can plot both equations in terms of x1. The system has a solution if they intersect
and the intersection coordinates are the solution of the system x1 and x2.
Example 4.1
We want to solve the system using the graphical method with MATLAB.
x=0:.1:8;
y1=9-x;
y2=1+.5*x;
y3=(abs(y1-y2));
I=y3/min(y3);
ind=find(I==1);
x1=x(ind)
x2=y2(ind)
plot(x,y1,x,y2)
xlabel('x1'),ylabel('x2')
grid
x1 =
5.3000
x2 =
3.6500
Matlab solution for Hw-1 Problem-1
9
6
x2
1
0 1 2 3 4 5 6 7 8
x1
The two plots of the two equations are shown in Figure 4.1. The solution of the system is
actually the values of x1 and x2 at the interception points x1=5.3 and x2=3.6.
There are many tools in MATLAB for solving systems of linear equations. In general,
suppose we have a linear system Ax = b. The matrix A is an m-by-n matrix and the
vector b is an m-dimensional column vector. We can use the left division \ to solve this
system.
a) Case m = n
For this case we calculate the exact solution. In MATLAB we define the matrix and the
column vector as
The known variables or the solution of the linear system equations can be obtained using
the left slash division
m = Y\z
m =
-1.0000
1.0000
0.0000
rez = z - Y*m
rez =
1.0e-015 *
0.1110
0.6661
0.2220
The residuals are very small and came from the rounding-off.
b) Case m > n
This system is called the over-determined system and is consistent in most cases. The
solution of this system using left division \ is the least square solution,
Let
Y = [2 1; 1 10; 1 2];
z = ones(3,1);
m = Y\z
m =
0.5849
0.0491
Residual values are shown in the following vector
rez = z - Y*z
rez =
-0.1208
-0.0755
0.3170
c) Case m < n
In this case the number of unknown variables exceeds the number of equations and this
system is defined as an under-determined linear system and its solution is consistent.
In MATLAB
Y = [1 2 3; 4 5 6];
z = ones(2,1);
m = A\b
m =
-0.5000
0
0.5000
The function rref returns a reduced row echelon form of the matrix
R = rref(A)
or
[R, pivot] = rref(A)
where pivot is a parameter used to hold the indices of the pivot columns.
A = magic(4);
b = ones(4,1);
To obtain the solution of the linear system Ax = b, the augmented matrix should be
transformed to the reduced echelon form. The solution of the system is stored in the last
column.
pivot =
1 2 3
x = x(:,5)
x =
0.0588
0.1176
-0.0588
0
b - A*x
ans =
0
0
0
0
length(pivot)
ans =
3
and the matrix A has a rank of 3.
The inverse matrix A-1 can be obtained using the inv command
E = inv(A)
E =
-2.1250 1.2500 -0.1250
1.9167 -1.1667 0.2500
-0.1250 0.2500 -0.1250
We can verify the above using the property A*A-1 = I and A-1*A = I,
A*E
ans =
1.0000 0.0000 -0.0000
0 1.0000 -0.0000
0 0.0000 1.0000
Similarly
E*A
ans =
1.0000 0 0
0 1.0000 -0.0000
0 0 1.0000
Pascal matrix: this matrix has several interesting properties and is defined in MATLAB
as pascal
A = pascal(4)
A =
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20
B = inv(A)
B =
4.0000 -6.0000 4.0000 -1.0000
-6.0000 14.0000 -11.0000 3.0000
4.0000 -11.0000 10.0000 -3.0000
-1.0000 3.0000 -3.0000 1.0000
The Cholesky triangle or upper triangular matrix of A is
C = chol(A)
C =
1 1 1 1
0 1 2 3
0 0 1 3
0 0 0 1
Note that the binomial coefficients are in the upper triangular part. To verify that we use
A = C'*C
ans =
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20
We can also compute the inverse of a matrix using the function rref introduced earlier.
We can use the above Pascal matrix A.
Let
A = pascal(4);
D = rref([A eye(size(A))]);
D = D(:, 5:8)
D =
4 -6 4 -1
-6 14 -11 3
4 -11 10 -3
-1 3 -3 1
D*A
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
4.6 Determinants
Many linear algebra applications require prior knowledge of the determinant of the
system matrix. We will examine some of these applications through examples. Now let
us identify the MATLAB built-in function det used to compute determinants.
A = magic(3);
det(A)
ans =
-360
We know that for a matrix A to be invertible, it must be square and its determinant not
equal to zero. This is one application in which we must know in advance the matrix
determinant in order to choose the appropriate solution method.
function ck = cofactor(A,k,l)
% ck: is the cofactors for matrix A.
[m,n]=size(A);
if m ~= n
error('Matrix must be square')
end
B = A([1:k-1,k+1:n],[1:l-1,l+1:n]);
ck=(-1)^(k+l)*det(B);
The following function d=youdet(A) can also compute the det of a matrix using the
cofactor expansion method [3].
function d=youdet(A)
% To compute the determinant of matrix A.
[m,n]=size(A);
if m ~= n
error('Matrix must be square')
end
a = A(1,:);
c = [];
for l=1:n
c1l = cofactor(A,1,l);
c = [c;c1l];
end
d = a*c;
The adjoint matrix is an important matrix used in solving systems of linear equations. We
can use the MATLAB adj(A) to compute the adjoint matrix.
function D=adj(A)
We can use the adjoint matrix along with the determinant to solve for the inverse matrix
A-1 = adj(A)/det(A)
Example 4.2
Find the solution of the following system using the left-division method.
3x 2y 9z 65
9 x 5 y 2 z 16
6 x 7 y 3z 5
3 2 - 9
A - 9 - 5 2
6 7 3
A = [3 2 9; -9 -5 2; 6 7 3];
det(A)
ans =
288
The determinant is not equal to zero and therefore the system has a unique solution
A = [3 2 9; -9 -5 2; 6 7 3];
B=[-65;16;5];
A\b
Ans=
2
-4
7
Therefore the system solution is: x=2, y=-4, z=7.
A*ans
ans=
-65
16
5
It is equal to vector b and therefore the answer is correct.
Example 4.3
Use the Gauss elimination method to solve the three unknowns of the following set linear
equations:
3x 2y 9z 65
9 x 5 y 2 z 16
6 x 7 y 3z 5
Also, write a MATLAB script file for the solution, showing the Gauss elimination
method.
3 2 -9 - 65
- 9 - 5 2 16
6 7 3 5
If we apply the Gauss elimination method in either the upper or the lower triangular form,
we will get the following answer regarding the unknowns:
x=2
y=-4
z=7
To solve the system with MATLAB, we need to use the following Gauss MATLAB
function [3].
function [ x ] = Gauss(a,b)
% solving system of linear equations with Gauss Elimination
% a: matrix with coefficients
% b: column victor
% X: known variables
ab=[a,b];
[R,C]=size(ab);
for j=1:R-1
for i=j+1:R
ab(i,j:C)=ab(i,j)/ab(j,j)*ab(j,j:C);
end
end
x=zeros(R,1);
x(R)=zeros(R,1);
for i=R-1:-1:1
x(i)=(ab(i,C)-ab(i,i+1:R)*x(i+1:R)/ab(i,i);
end
end
[A]=[L][U]
where [L] is the lower triangular matrix and [U] is the upper triangular matrix.
In the lower triangular matrix all elements above the diagonal are zero, in the upper
triangular matrix, all the elements below the diagonal are zero. For example, for a 3-by-3
matrix A, its LU decomposition looks like this:
The following DC electrical circuit has three current loops, I1, I2, and I3. The mesh
equations are also provided.
20 4 10 I1 30
4 18 11 I 18
2
10 11 30 I 3 20
%Example 4.4
clear all
A=[20 -4 -10;-4 18 -11;-10 -11 30];
b=[30;-18;20];
A1=A;A1(:,1)=b;
A2=A;A2(:,2)=b;
A3=A;A3(:,3)=b;
D=det(A);D1=det(A1);D2=det(A2);D3=det(A3);
X(1)=D1/D;X(2)=D2/D;X(3)=D2/D;
x'=
2.4732
0.5939
1.7088
b)
clear all
A=[20 -4 -10;-4 18 -11;-10 -11 30];
b=[30-18 20];
x=Gauss(A,b)
x'=
2.4732
0.5939
1.7088
c)
d)
clear all
A=[20 -4 -10;-4 18 -11;-10 -11 30];
b=[30;-18;20];
A1=A;A1(:,1)=b;
A2=A;A2(:,2)=b;
A3=A;A3(:,3)=b;
D=det(A);D1=det(A1);D2=det(A2);D3=det(A3);
X(1)=D1/D;X(2)=D2/D;X(3)=D2/D;
x';
[L,U]=lu(A);
z=L\b;
x=U\z;
x
x=
2.4732
0.5939
1.7088
4.10 Vectors
The Euclidean norm known as the 2-norm of a vector can be computed using the
MATLAB norm function.
Let
a = -2:2
a =
-2 -1 0 1 2
The 2-norm is
twon = norm(a)
twon =
3.1623
To compute the angle between two equal size vectors we need to use,
= arccos(a.b/||a|| ||b||),
where ||a|| is the norm of vector a, a.b stands for the dot product of a and b and arccos is
the inverse cosine function.
a = -2:2;
b = (1:5)';
Then
angle = acos((a*b)/(norm(a)*norm(b)))
angle =
1.1303
Note that the linear system Ax = b will possess a solution with this condition only:
rank(A)=rank( [A b] ).
are the ordered bases of two vector spaces. We can use the above transmit function to
find the transition matrix
E = transmat(T, S)
E =
3 4
1 2
[V, D] = eig(A)
The two outputs V and D are matrices of the same size as matrix A. The eigenvectors are
stored in columns of matrix V where eigenvalues are stored in the diagonal entries of
matrix D.
A = pascal(4);
[V, D] = eig(A)
V =
0.3087 -0.7873 0.5304 0.0602
-0.7231 0.1632 0.6403 0.2012
0.5946 0.5321 0.3918 0.4581
-0.1684 -0.2654 -0.3939 0.8638
D =
0.0380 0 0 0
0 0.4538 0 0
0 0 2.2034 0
0 0 0 26.3047
function B=code(s, A)
p = length(s);
[n,n] = size(A);
b = double(s);
r = rem(p,n);
if r ~= 0
b = [b zeros(1,n-r)]';
end
b = reshape(b,n,length(b)/n);
B = A*b;
B = B(:)';
function s=dcode(B, A)
[n,n]=size(A);
p = length(B);
B = reshape(B,n,p/n);
d = A\B;
s = char(d(:)');
Problems
1.Create a row vector of length N=20 whose components are all equal to two without
entering the number two more than once.
2. Consider the given row vector a = [5 6 7 8 9]. Create a column vector b with the same
components but reversed order.
3. The MATLAB built-in function sort(a) is used for sorting components in ascending
order. Now we are required to sort vector a in descending order.
4. Without using function max (min), find the smallest and largest element or entry of a
given vector.
5. Create a row vector of random integers uniformly distributed in the interval (2, 10)
using function rand.
Hint: function fix might be helpful.
6. The matrix A is a square matrix. Create a matrix B whose entries are the same as those
of A except that the main diagonals are ones.
7. We have matrices A and B which are square and invertible and a column vector b and
all have the same number of rows. We want to solve the linear system equation ABx = b
using backslash \. and without conducting the matrices product A*B.
10. Compute the rank of the given matrices using the MATLAB rref function
(a) C = magic(4)
(b) C = magic(5)