MATLAB Basics
MATLAB Basics
MATLAB Fundamentals
The MATLAB provides the extensive tutorials for all its products in various format.
This appendix briefly introduces the MATLAB fundamentals based on the
MATLAB Primer. You can observe the primitive MATLAB capabilities in short.
Once you click the MATLAB icon, you will get the following screen as Fig A.1.
We can observe the four window spaces as below.
– Current Folder: Your working directory and files.
– Command Window: Enter commands for immediate execution.
– Workspace: Variables and data.
– Editor-Untitled: Once click the New button, the editor window provides the
script space for programming.
Most of the icon buttons and ribbon menus are intuitive and self-explanatory for
its functions. We can execute the MATLAB commands by
– Type the command in command window and put the <enter> key
– Write the program in the editor window and put the <ctrl>+<enter> key
The script program also can be executed by clicking the run button. One big
advantage of the MATLAB programming is the worry-free variables. If we need the
variables, just create and use them. Below example creates the a and b variable with
initial values in command window. As soon as we type the ‘a=1’ and <enter>, the
a variable is created with initial value one. When we compute the value without the
assignment, the output value is allocated at the temporary variable ans. See the ‘a+b’
command in below. All created variables can be seen in the workspace window.
>> a = 1
a=
1
>> b = 2
b=
2
>> a+b
ans =
3
>>
To clear the command window, type the clc. The second MATLAB advantage is
the strong supports for the linear algebra operations based on the matrix and array.
Just like variable, we can create the matrix and array as below.
Appendix A: MATLAB Fundamentals 647
>> a = [1 2 3]
a=
1 2 3
>> b = [4, 5, 6]
b=
4 5 6
>> c = [7; 8; 9]
c=
7
8
9
>> d = [1 2 3; 4 5 6; 7 8 9]
d=
1 2 3
4 5 6
7 8 9
>> e = d*a
Error using *
Incorrect dimensions for matrix mulplicaon. Check that the number of
columns in the first matrix matches the number of rows
in the second matrix. To perform elementwise mulplicaon, use '.*'.
>> e = a*d
e=
30 36 42
>>
The most arithmetic operators in MATLAB perform the linear algebra opera-
tions which require to match the dimensions between the matrices. Table A.1
shows the arithmetic operator list. The addition and subtraction are working for the
constant, matrix, and element-wise operation.
Other operators for logic and relation are listed below as Table A.2.
The matrix can be generated by the MATLAB functions. The part of functions is
shown below in Table A.3.
Below example demonstrates the matrix generation from the function. The first
command rng(‘default’) places the random number generator setting to their default
values so that they produce the same random numbers.
648 Appendix A: MATLAB Fundamentals
>> rng('default')
>> aa = rand(3,3)
aa =
0.8147 0.9134 0.2785
0.9058 0.6324 0.5469
0.1270 0.0975 0.9575
>> bb = ones(3,2)
bb =
1 1
1 1
1 1
>>
The matrix is also produced by the concatenation which joins the arrays to make
larger ones. See below example.
>> rng('default')
>> bb = randi(10,2,3)
bb =
9 2 7
10 10 1
>> cc = [bb bb]
cc =
9 2 7 9 2 7
10 10 1 10 10 1
>> dd = [bb, bb]
dd =
9 2 7 9 2 7
10 10 1 10 10 1
>> ee = [bb; bb]
ee =
9 2 7
10 10 1
9 2 7
10 10 1
>>
650 Appendix A: MATLAB Fundamentals
Use the indexing, we can access or modify selected elements of an array. The
most general method is to indicate row and column number which starts from one.
A single column-wise numbering can specify the matrix position as well. The
matrix element can be modified by assigning the specific value to the element.
>> bb = randi(100,4,4)
bb =
23 54 11 82
92 100 97 87
16 8 1 9
83 45 78 40
>> bb(2,4)
ans =
87
>> bb(14)
ans =
87
>> bb(2,4)=0
bb =
23 54 11 82
92 100 97 0
16 8 1 9
83 45 78 40
>> bb(2,1:3)
ans =
92 100 97
>> bb(:,2)
ans =
54
100
8
45
>> bb(end,:)
ans =
83 45 78 40
>> cc = 0:5:30
cc =
0 5 10 15 20 25 30
>> dd = 1:10
dd =
1 2 3 4 5 6 7 8 9 10
>>
Appendix A: MATLAB Fundamentals 651
The colon operator allows to refer the multiple elements in the matrix as the
start:end form. The colon alone indicates all of the elements in that dimension. The
end indicator denotes the last row or column number. The general colon operator
creates an equally spaced vector using the form start:step:end. Missing the step
value indicates the default step value of one.
MATLAB provides a large number of functions which perform various tasks.
The input and output argument format can be found by using the help or doc
function as below. Note that doc function opens the new window for information.
One example of function usage is to find the minimum, negative, and zero
locations of the given function below.
y ¼ x2 1 for 10 x 10
x2 1 ¼ 0
The MATLAB numerically computes the values based on the discretized input
values for the given range. The continuous input is divided into the discrete input
with 0.1 step by using the colon operator. The output is calculated by the
element-wise operation. The min and find function perform the designated tasks.
Note that the fine-grain results can be derived from the reduced step size for input.
652 Appendix A: MATLAB Fundamentals
In general, the function supports the various argument styles. See help for further
information. Below example is written by the script editor.
k1 =
-1
I1 =
101
k2 =
92 93 94 95 96 97 98 99 100 101
102 103 104 105 106 107 108 109 110
ans =
Columns 1 through 13
-0.1900 -0.3600 -0.5100 -0.6400 -0.7500 -0.8400 -
0.9100 -0.9600 -0.9900 -1.0000 -0.9900 -0.9600 -0.9100
Columns 14 through 19
-0.8400 -0.7500 -0.6400 -0.5100 -0.3600 -0.1900
k3 =
91 111
ans =
0 0
The third advantage of the MATLAB is the powerful visualization tools. The
impressive 2-D and 3-D plots are available with various decoration functions to
display extensive information. Labeling, legend, range, and etc. are specified by the
MATLAB functions. Using the TeX markup, Geek letters and special characters
can be added to the plot. Some of the list are arranged below in Table A.4.
Appendix A: MATLAB Fundamentals 653
x = 0:pi/100:2*pi; % Input
y1 = sin(x); % sine funcon
y2 = cos(x); % cosine funcon
figure,
plot(x,y1,x,y2), grid % Line plot for sine and cosine
tle(‘Example 1’) % Title
legend('sin(\omega)','cos(\omega)'); % Legend with special char
xcks([0 pi/2 pi 3*pi/2 2*pi]) % Tick posion
xcklabels({'0','\pi/2','\pi','3\pi/2','2\pi'}) % Tick label
xlim([0 2*pi]) % x display range
ylim([-1.5 1.5]) % y display range
xlabel('\omega') % x label
ylabel('Magnitude') % y label
figure,
subplot(211), stem(x,y1), grid % Subplot with stem
tle(‘Example 2’)
ylabel('sin(\omega)')
xcks([0 pi/2 pi 3*pi/2 2*pi])
xcklabels({'0','\pi/2','\pi','3\pi/2','2\pi'})
xlim([0 2*pi])
subplot(212), stem(x,y2), grid
ylabel('cos(\omega)')
xcks([0 pi/2 pi 3*pi/2 2*pi])
xcklabels({'0','\pi/2','\pi','3\pi/2','2\pi'})
xlim([0 2*pi])
xlabel('\omega')
654 Appendix A: MATLAB Fundamentals
Example 1
1.5
sin( )
cos( )
1
0.5
Magnitude
-0.5
-1
-1.5
0 /2 3 /2 2
The simple sine and cosine plots are displayed for 2p range as below (Fig A.2).
The subplot function allows us to place the more than one plot in the single
figure as Fig A.3.
The MATLAB also gives the versatile 3-D plot features. Below example pre-
sents the 3-D Gaussian plot according to the following equation.
Example 2
1
0.5
sin( )
-0.5
-1
0 /2 3 /2 2
0.5
cos( )
-0.5
-1
0 /2 3 /2 2
figure,
surf(X,Y,Z) % 3D surface plot
tle('3-D Normal Distribuon') % Title
xcks([-2 -1 0 1 2]) % Tick posion
xcklabels({'-2','-1','x_0','1','2'}) % Tick label
xlabel('x') % x axis label
ycks([-2 -1 0 1 2]) % Tick posion
ycklabels({'-2','-1','y_0','1','2'}) % Tick label
ylabel('y') % y axis label
zlabel('e^{-((x-x_0)^2+(y-y_0)^2)}') % z axis label
colormap('gray') % Color bar color configuraon
colorbar % Color bar
656 Appendix A: MATLAB Fundamentals
0.9
1
0.8
0.8 0.7
+(y-y ) )
2
0
0.6 0.6
2
e -((x-x 0 )
0.4 0.5
0.4
0.2
0.3
0
2 0.2
1 2
y0 1 0.1
x0
-1
-1
y -2 -2
x
Prior to create the 3-D plot, we must generate the input coordinates for the 3-D
equation. The meshgrid function returns 2-D grid coordinates based on the coor-
dinates contained in input vector(s). The X and Y are the square grid coordinates
with single input grid size. The element-wise operation completes the equation
calculation followed by the 3-D plot function. Below figure shows the 3-D surface
plot. We can change the viewpoint by clicking the rotate 3D button and dragging
the figure (Fig A.4).
We can create the MATLAB function by generating the new script for function
as shown in Fig A.5.
The created editor includes the function format as below. Decide function name,
write function code, and update the comment. Finally save the function as the
function name with m extension.
Save the function as Mysum.m in the working directory. The help function with
Mysum replies the comment in the function as shown below. Execute the comment
example for verification.
658 Appendix A: MATLAB Fundamentals
We can execute the part of MATLAB program code as section. Sometime, this
kind of execution is required for debugging. The double percent sign (%%) divides
the program into the sections as shown in Fig A.6. By moving the cursor, the
selected section is highlighted by yellow color as shown below. Typing the <ctrl>
+<enter> executes the chosen section. MATLAB provides the advanced debugging
tools and the section run is the part of them.
In command window, the command history is recalled by clicking the <up> key
and the history is narrowed by typing the character letters as shown in Fig A.7. The
quick access to the history makes the multiple executions easy for various purpose.
Followings are the frequently used commands.
clear all: Clear all variables
clc: Clear the command window
clf: Clear the current figure
close all: Close all figure windows
lookfor ‘keyword’: Search all MATLAB files for keyword
Further information about the MATLAB and toolboxes can be referred from the
MathWorks documentations.
Appendix A: MATLAB Fundamentals 659
Symbolic math performs exact computation with variables which have no given
value as symbols. Symbolic math toolbox provides functions for solving and
manipulating symbolic math equations. The toolbox delivers functions in subjects
such as calculus, linear algebra, differential equations, equation simplification, and
equation manipulation. The computations can be realized either analytically or
using variable-precision arithmetic. The MATLAB live script editor presents the
optimal environment to create and run the symbolic math code. We can share the
symbolic work with other users as live scripts or convert them to HTML or PDF for
publication. We can generate the new live script by selecting the New ! Live
Script in the menu as below Fig B.1.
The live script is divided into the text and code area. The text area (white)
describes the background, algorithm, explanation, analysis, etc. with plain text. The
code area (gray) locates the MATLAB code for algorithm execution.
The MATLAB outcome is embedded at the live script immediate right or below
according to your choice as shown in Fig B.2.
The buttons under the LIVE EDITOR ribbon menu specify the file, text, code,
and execution related information. The buttons are intuitive and self-explanatory.
Example live script code is below. Note that the below is not the symbolic math
code. Execute the code by clicking <ctrl>+<enter>.
Appendix B: MATLAB Symbolic Math Toolbox 663
Title
Heading
Normal
% Code
x = 0:pi/100:2*pi; % Input
y1 = sin(x); % sine funcƟon
y2 = cos(x); % cosine funcƟon
plot(x,y1,x,y2), grid % Line plot for sine and cosine
Ɵtle('Example 1') % Title
legend('sin(\omega)','cos(\omega)'); % Legend with special char
xƟcks([0 pi/2 pi 3*pi/2 2*pi]) % Tick posiƟon
xƟcklabels({'0','\pi/2','\pi','3\pi/2','2\pi'}) % Tick label
xlim([0 2*pi]) % x display range
ylim([-1.5 1.5]) % y display range
xlabel('\omega') % x label
ylabel('Magnitude') % y label
Most type of MATLAB code can be executed in the live script. The graphic
environment of live script gives the powerful presentation for the symbolic math
code which use the mathematical symbols and characters frequently. Now, we will
explore the symbolic math toolbox with live script editor. Below example shows
the symbolic math example.
664 Appendix B: MATLAB Symbolic Math Toolbox
The above code performs the symbolic computations for simple calculus. The
symbolic math toolbox supports extensive calculus functions such as differentia-
tion, integral, vector operations, series, limits, transformation, and etc.
666 Appendix B: MATLAB Symbolic Math Toolbox
Solve equations
clear all
syms x y z
z1 = x^3-6*x^2
z1 =
z2 = 6-11*x
z2 =
solve(z1==z2)
ans =
solve(z1-z2==0)
ans =
y=
z=
Appendix B: MATLAB Symbolic Math Toolbox 667
We can solve the multi or single variable polynomials as above. The symbolic math
toolbox provides the equation solvers for polynomials and differential equations.
Manipulation of polynomials
syms x y
f1 = (x^2- 1)*(x^4 + x^3 + x^2 + x + 1)*(x^4 - x^3 + x^2 - x + 1)
f1 =
expand(f1) % Expand polynomial
ans =
f2 = x^3 + 6*x^2 + 11*x + 6
f2 =
factor(f2) % Factor polynomial
ans =
f3 = x^5 + x^4 + x^3 + x^2 + x
f3 =
horner(f3) % Nested representaon for polynomial
ans =
f4 = 2*x^2 - 3*x + 1
f4 =
aa = subs(f4,1/3) % Substute the x with 1/3
aa =
f3 = subs(f2,n,(-20:20)+eps);
% Substute n with -20:20 with eps to avoid the 0/0
f4 = eval(f3); % Compute the substuon
f4(21) % Approximated h[0]
ans = 0.2500
temp = limit(f2,n,0) % Verify real h[0]
temp =
The above code performs the inverse DTFT to design the LPF with cutoff
frequency p=4. The corresponding impulse response is displayed as stem plot. Note
that the simplify function makes the equation in simple form. The substitution is
executed to replace the n symbolic variable with range of integer values. In zero
Appendix B: MATLAB Symbolic Math Toolbox 669
f2 = x^2 + y^2
f2 =
fsurf(f2) % Surface plot of symbolic funcon (auto range)
xlabel('x')
ylabel('y')
tle(texlabel(f2))
grid on
670 Appendix B: MATLAB Symbolic Math Toolbox
Again, there is no given value to the symbolic variables. This condition is also
true for drawing the plot in symbolic math. We only assign the symbolic function to
the designated plot functions to illustrate the plot as shown above.
Assumptions
clear all
syms n x
f1 = sin(2*n*pi) % Given funcon1
f1 =
simplify(f1) % Simplify funcon1
ans =
assume(n,'integer') % Assume that n is integer
simplify(f1) % Re-simplify funcon1
ans = 0
f2 = x^4==1 % Given funcon2
f2 =
solve(f2,x) % Solve funcon2
ans =