Chapter 1
Basic Matlab Commands
1.1 Introduction
Matlab is one of the most powerful tools in computation, numerical analysis and system
design. Its user friendly environment, in addition to its powerful computational kernel
and graphical visualization capabilities make it an integral part of the control system
design, optimization and implementation.
Along with the basic Matlab command package, several additional toolboxes have been
developed for specific purposes that extend Matlab’s capabilities. Examples are Simulink,
Control Systems Toolbox, Fuzzy Logic Toolbox, Image Processing Toolbox, Statistics and
Machine Learning Toolbox and many more.
In this chapter, the basic Matlab commands for manipulating and plotting variables
shall be presented. Firstly though, the program’s interface needs to be explained. The
window is divided into three main parts.
7
CHAPTER 1. BASIC MATLAB COMMANDS 8
The Command Window is the main window where the commands are inputed. The
Current Directory shows the directory from which Matlab runs the files and functions we
have created. Command History shows the history of all the commands that we input
into the Command Window. The main menu has three different tabs, HOME, PLOTS
and APPS. From the Home tab the appearance and layout of Matlab can be changed.
1.2 Input Data
Matlab’s basic data structure is the matrix. Of course scalar variables and vector belong
to the same category of data. In order to define a new variable in matlab, the following
formula is used
variable name= value
% or
variable name= value;
where value represents a numerical value. The ; at the end of the command determines
whether the result will be displayed on screen or not. For example, if we define a 1000
column array representing a time interval, there is no point in displaying the result on
screen. From the above code it is also seen that we use the symbol % to input comments
in our code.
There are two more useful methods of inputting data. The first one is the formula to
be used when creating matrices, which is
M=[a,b; c,d]
where the symbols [] represent the beginning and end of a matrix and the symbol ; here is
used to denote a new line of the matrix. Needles to say, when defining a matrix variable
the number of elements in each row must be the same, otherwise an error message is
displayed. To choose among certain elements of a matrix, one can simply use parentheses
() to define which element or which parts of the matrix are to be chosen. To do so, inside
the parentheses the specific rows and columns are specified. To choose all the columns or
all the rows, use the symbol :. This will be made clear in the next example.
The second formula is useful when creating arrays of equally spaced numbers. This is
particularly useful when creating time intervals, but is also used inside ”for” loops. The
command is
t=a:step:b
where a and b represent numbers and step is the step value used. If the step is omitted,
the default value is 1. A second way uses the following command
CHAPTER 1. BASIC MATLAB COMMANDS 9
t=linspace(a, b, n)
that creates an array of n equally spaced numbers between a and b. As an example, the
following commands
M=[1 5 10, 6 7 8]
t1=[Link]
t2=linspace(0,5,4)
M(1,2)
M(:,2)
M(1,[2 3])
create three variables with the following values
1 5 10
M= t1 = 0 2 4 t2 = 0 1.6667 3.3333 5.0000
6 7 8
and the last 2 commands create the arrays
5
5 5 10
7
One last useful command is the clear command, which deletes any variable in the
workspace. Its syntax is the following
clear variable name % deletes variable
clear %deletes all variables
clc % clears the command window (does not delete any variables)
1.3 Math Operations and Functions
There are many already available functions that the users can use in order to solve a
problem. The typical syntax for a function is to call the function using the desired input
arguments. The function will return its outputs, which should be saved in new variables
i.e.
[output1,output2,. . .]=function name(input1,input2,. . .)
the simplest examples of matlab functions are cos(x), sin(x), tan(x), log(x), ...
exp(x), sqrt(x) that take as an input a numerical variable and return a unique output.
An example of a more complex Matlab function is ss(a,b,c,d) that is used to define
a new state space system and requires four input arguments. It should be noted here
CHAPTER 1. BASIC MATLAB COMMANDS 10
that for calling a multi-input multi-output function, one uses parentheses for the input
arguments and brackets for the multiple variable assignments.
In general, in order to find out about a function’s syntax, input and output arguments
and general informations about its functionality, the command
help function name
displays all the available information on the function, as well as examples and other
relevant functions. Try for example help eig.
Regarding mathematical operations, Matlab uses the traditional symbols + - * ...
ˆ /. What should be noted though, is that Matlab treats the operators using linear
algebra rules. So if one wishes to use element-wise operations, this should be specified
using .* .ˆ ./ instead. For example, in order to obtain the square of each element in a
vector, the following commands should be used
t=0:0.1:10; % Example of a vector
t.ˆ2 % In order to obtain the square of each element
% The command tˆ2 tries to multiply t*t, which is wrong since it does ...
not satisfy the linear algebra rules.
Some other useful matrix functions are the following
inv(M) Matrix inverse
pinv(M) Pseudoinverse
eig(M) Eigenvalues of a matrix
eye(r,c) Create an r × c matrix with ones in the diagonal
zeros(r,c) Zero r × c matrix
rand(r,c) An r×c matrix of pseudo random values drawn from the
standard uniform distribution on the open interval(0,1)
diag(M) Diagonal matrix with the elements M in its diagonal
m' Conjugate transpose of matrix m
1.4 Graphs and Figures
Plotting is one of the most useful applications of any programming language. Matlab
offers a variety of plotting tools that help visualize data, both continuous and discrete.
In order to plot a function, three basic steps are required. First define the range of
values over which we wish to plot the function, then define the function and lastly, call a
plotting command.
Depending on the kind of data we wish to visualize, different plot commands should
be used. The most basic are covered in the following table
CHAPTER 1. BASIC MATLAB COMMANDS 11
plot(x,y,'details') Plots vector y versus vector x. In 'details', graph
details are entered (optional)
plot3(x,y,z) Plots a line in R3 through the points whose coordinates
are (x,y,z)
surf(x,y,z) Plots the coloured parametric surface defined by (x,y,z)
surfc(x,y,z) Plots the coloured parametric surface defined by (x,y,z)
in combination with a contour plot
mesh(x,y,z) Plots the coloured parametric mesh defined by (x,y,z)
meshc(x,y,z) Plots the coloured parametric mesh defined by (x,y,z) in
combination with a contour plot
contour(x,y,z) Contour plot, i.e. the level curves of function z over the
coordinates (x,y)
in the plot command, the optional argument 'details' is a string containing informa-
tion about the way the data are plotted. The string can contain one character from each
of the following columns
b blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star (none) no line
y yellow s square
k black d diamond
w white v triangle (down)
ˆ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
For example, the commands
t=0:0.2:2*pi;
x=cos(t);
plot(t,x,'--')
will plot the cosine signal over [0,2π] and plot its graph as a dashed line, as will be seen
in the following examples.
Other useful commands to change the appearance of a figure are the following
CHAPTER 1. BASIC MATLAB COMMANDS 12
xlabel('text') Text on the x-axis
ylabel('text') Text on the y-axis
title('text') Title text
grid Puts grid on the graph
axis on Displays the axes
axis off Hides the axes
axis square Makes the figure square
axis equal Makes the unit of measure equal to both axes
axis([ xmin xmax ymin ymax]) Sets axes limits
hold on Holds the current plot
legend('first', 'second',. . .) Inserts legend
Now, what happens if the user desired to plot different functions on the same figure, while
keeping the previous ones too. That is useful for example when we want to observe the
changes in the response of the system under perturbations of a single parameter. By
default, the plot command will plot a new figure in the same window, deleting the old
ones. In order to keep the previous plots, one can use the command hold all. For
example, using
t=0:0.2:2*pi;
x=cos(t);
y=5*cos(t);
plot(t,x)
hold all
plot(t,y)
will draw these 2 functions on the same graph, using different colours for them.
On the other hand, what if we want to plot new data on different windows? Matlab
offers two options for this. We can either create a new blank figure with a different key
number, or create a subplot.
In the first option, simply by inputting the command figure(n) Matlab creates a
new blank figure under the key number n = 1, 2, .... all plot commands following this
command will be visualised in this new window.
On the other hand, the command subplot(n,m,i) creates a figure and splits it in
n rows and m columns. Every new plot command will be visualised in the subfigure at
position i, counting from right to left and top to bottom. To move to another subfigure j
we enter the command subplot(n,m,j). So for example:
t=0:0.2:2*pi;
x=cos(t);
y=sin(t);
subplot(1,2,1)
plot(t,x)
subplot(1,2,2)
CHAPTER 1. BASIC MATLAB COMMANDS 13
plot(t,y)
will plot a 2 × 2 figure having the cosine graph on the first window and the sine graph on
the second window. Examples of these commands are given in the next section.
1.5 Examples
Example 1.5.1. Plot the function x(t) = cos(t) for 0 < t < 4π.
Solution.
t=0:pi/180:4*pi;
x=cos(t);
plot(t,x,'g--')
xlabel('time')
ylabel('cosine')
title('Example')
grid
legend('cosine')
Example 1.5.2. Create a 2 by 2 figure with the functions cos(t), sin(t), et and log(t) for
0 ≤ t < 4π.
Solution.
CHAPTER 1. BASIC MATLAB COMMANDS 14
t=0:0.1:4*pi;
subplot(2,2,1)
plot(t,cos(t))
title('cosine')
grid
subplot(2,2,2)
plot(t,sin(t))
title('sine')
grid
subplot(2,2,3)
plot(t,exp(t))
title('exponential')
grid
subplot(2,2,4)
plot(t,log(t))
title('log')
grid
Example 1.5.3. Plot the function x(t) = eλ t for λ = −1, −2, −3, −4 and 0 ≤ t < 10 on
the same graph.
Solution.
t=0:0.1:10;
hold all
for i=1:4
plot(t,exp(-i*t))
end
grid
CHAPTER 1. BASIC MATLAB COMMANDS 15
Example 1.5.4. Making use of the commands sphere and meshgrid, plot the unit
sphere and the function f (x, y) = −cos(x) − cos(y) + 1 on the same figure.
Solution. We will plot the unit sphere for N=20, and then the surface over the region
−2 ≤ x, y ≤ 2.
%% For the sphere
[x,y,z]=sphere(20);
surf(x,y,z)
hold all
%% For the surface
[x,y]=meshgrid(-2:0.2:2);
surf(x,y,-cos(x)-cos(y)+1)
grid
The resulting graph is a sphere “sitting ”on the bottom of the surface.
CHAPTER 1. BASIC MATLAB COMMANDS 16
Example 1.5.5. Making use of the command meshgrid, plot the surface f (x, y) =
2 2
x · e−x −y along with its contour plot.
Solution. We will plot the surface over the region −2 ≤ x, y ≤ 2 using the command
surfc.
[x,y] = meshgrid([-2:.2:2]);
surfc(x,y,x.*exp(-x.ˆ2-y.ˆ2))