1 Basic Element of Matlab
1 Basic Element of Matlab
Contents
1 What is MATLAB?...................................................................................................................... 3
5 Arrays ......................................................................................................................................... 14
5.5 Transposition....................................................................................................................... 21
9 Exercises .................................................................................................................................... 31
MATLAB is a computer program designed for technical calculations. Its name is an abbreviation
of "Matrix Laboratory". In this program, matrix computations are implemented in a
straightforward manner. However, many other pre-programmed routines are available. In addition,
it is possible to implement user-defined calculation routines. MATLAB allows users to implement
calculations in relatively short programming time. When these calculations have been performed,
they can be visualized by means of several plot-routines.
MATLAB can be extended with so called toolboxes. In general, these are collections of MATLAB
functions that are tailored for special classes of problems. The ‘(Extended) Symbolic Math
Toolbox’ is an exception. To a great extent, this toolbox consists of ingredients from the computer
algebra package MuPAD. MATLAB performs calculations with the aid of matrices. These are
rectangular schemes of numbers, which are also called arrays. The `Symbolic Math Toolbox' is
quite different from MATLAB itself, since symbolic calculations hardly make any use of arrays.
For this reason it is important to know whether a function used is a MATLAB function or a
`Symbolic Math Toolbox' function. This will not be completely clear at the outset, but it will
become clearer after regular use of MATLAB.
MATLAB can be started by clicking on the selecting the "MATLAB" option in your startup tree
or possible on your Windows desktop. When MATLAB is started, a window similar to the one
below should appear:
The main window in MATLAB is the command window, positioned at the lower right cornor, in
which commands can be typed after the MATLAB prompt:
>>
Commands are entered with the ‘return’ key. The command is then executed by MATLAB. If
MATLAB is ready, after possible outputs a new prompt appears.
The window on the left is the "Current Folder" window. The "Current Folder" window depicts the
files in the current directory. This is the first user-governed directory where MATLAB will look
for files or functions. On the top right you will find the "Workspace" window, in which all declared
variables are shown. The bottom right window is the "Command history", where you can find all
By clicking on the "Command Window", after the MATLAB prompt >>, a command can be typed.
After having pushed the ‘return’ key, the command is executed, and possibly the result appears on
the screen. A command and its result looks like this:
>> a = 1 + 2 + 3
a =
6
The result of 1 + 2 + 3 is assigned to the variable a. You can now use this variable in successive
operations, such as:
In MATLAB, variables are introduced by assigning a value. Note, that the value can be numerical
values, matrices (called arrays), or other types. You can use the variable, and later possibly assign
a new value to the variable. It is not possible to perform calculations with variables that have not
been assigned a value.
A command does not need to start with an assignment of the form variable =. In such a case, the
result is automatically assigned to the variable ans. You can then use ans further.
>> 4*a + 1
ans =
25
>> ans*ans
ans =
625
If you now want to know what the value of a is, the following command suffices:
>> a
a =
6
Normally, MATLAB displays the output below the command. The output is suppressed by ending
the command with a semicolon. After having entered the command s=1+2, the screen looks as
follows
The value 3 has been assigned to the variable s. If you want to know the value of this variable, you
can either look in the “Workspace” window on the top left of your MATLAB window, or request
the value of s as follows
>> s
s =
3
If a command is longer than one line, you can end the line with three dots, and then press the
‘return’ key. You can then continue on the following line. After completing the command, the
screen looks as follows:
>> s = 1 + 2 + ...
3 + 4
s =
10
You cannot enter mathematical expressions literally. The Tables 1.1-1.2 make clear how
mathematical expressions can be entered. The variables in these tables are to be interpreted as
numbers.
Remark: The order of operations in MATLAB is the standard order: first raising to a power, then
multiplication and division, and after that addition and subtraction. To deviate from this sequence,
3.2 Interruption
A (long) MATLAB calculation can be interrupted with ‘ctrl-c’. After this, a new prompt appears
and new commands can be entered. This interruption is especially useful when a programmed loop
is running that is corrupt.
If a command is incomplete or invalid and you press the `return' key, there are two possibilities:
An error message and a new MATLAB prompt appear. You can start over again.
The flickering cursor is at the left of the line below the command. In this case there are two
possibilities.
o The command can be finished and after that evaluated.
o Using ‘ctrl-c’, you can interrupt entering the command. A new MATLAB prompt
appears.
3.4 Variables
The name of a variable in MATLAB has to start with a letter. After that, the name can consist of
an arbitrary number of letters, numbers or symbols like '_' and '-'. MATLAB does distinguish
between upper and lower case letters.
because
i or j The complex number i with the property that i2 = -1.
pi 3.1415...
Inf This is the value infinity. When one divides 1 by 0, 1/0, the result will be Inf.
NaN This variable is a representation of `Not a Number'. A calculation with NaN
always results in NaN. The command 0/0 produces NaN.
Warning: in principle, it is possible to assign a value to the internal MATLAB variables presented
in Table 1.3. This can influence your calculations. Therefore, it is wise never to assign a value to
an internal MATLAB variable. Commands like >>pi=10 should be avoided at all times! If by
accident you have given a different value to an internal MATLAB variable, you can remove this
value by using clear or the workspace browser.
On the top right of the default MATLAB window, you will find the "Workspace" window where
all variables in use are listed. The browser also indicates to which class the variables belong. If
necessary, you can remove variables by using the browser. The special variables above will not be
listed.
Some other important commands for the management of variables are given in Table 1.4.
In principle all information about MATLAB can be found in MATLAB's help facilities. Since the
MATLAB commands and functions can often be used in more general situations, the information
you will obtain through the help facilities will often be more general than necessary. You will have
to filter out the essential ingredients from the information that is offered.
Below we list the most important ways to use the MATLAB help facilities.
Help Functions - By typing the command >> help 'function name' in the Command
Window, an M-help file appears in the Command Window. This file contains a short
description of the function, the syntax, and other closely related help functions. This is
MATLAB's most direct help facility, and you will often use this facility to quickly check
how a certain function works and which notation should be used. If more extensive results
are needed, try the command doc.
Look for - By typing the command lookfor 'topic' in the Command Window, you can
call up all help possibilities which contain the specific search word. You can use this
possibility to look for a function of which you do not remember the function name exactly.
In this manner, all related topics appear in the Command Window.
Help Browser - You can use the `Help Browser' to find and browse information about
Mathworks products. This help browser contains different ways to obtain the correct
information, like lists, a global index and a search function. You will especially use this
help facility if you are looking for a function of which you do not remember the name.
More information about the Help Browser can be found in the next paragraph.
Other help facilities - You can use product specific help facilities, have a look at
Mathworks' demos by typing demos in the Command Window, consult the Technical
Support, look for documentation about other Mathworks products, have a look at a list or
other books, and take part in a MATLAB newsgroup. More information about these topics
can be found in the MATLAB Help Browser or on the site www.mathworks.com.
You can use the "Help Browser" to look for documents and to have a look at MATLAB documents
and other Mathworks products. The "Help Browser" is a html viewer that is integrated in the
MATLAB desktop. With this browser you can look at the HTML documents belonging to
MATLAB.
You can open the "Help Browser" in three different ways:
When the "Help Browser" is opened, a window similar as the one below will appear:
The Help Browser consists of two parts. The upper part called the Help Navigator/Search box, can
be used to find information. In the lower part you can look at the documentation. Below, the
different tabs of the navigator are listed:
When you know the name of a MATLAB command you want to use, e.g. the function plot, the
fastest way to obtain information is to type
This will show you some help in the command window. An alternative is to use the command doc
plot that will open the help browser containing a more extensive explanation, sometimes
containing examples.
If you do not know the name of a function or do not know whether such a function exists, using
the command lookfor function or the Help Browser would be appropriate
MATLAB uses matrices (or arrays) as the basic calculation unit. An array is a rectangular scheme
of numbers, called elements, arranged in rows and columns. The simplest array contains
only one column or one row.
An array with one row is also called a row or a row vector, and an array with one column is also
called a column or a column vector. If the difference between consecutive elements in a row is
always the same, the row can be formed with the command:
Here ‘initial value’ is the first element of the row, ‘final value’ is the last element of the row, and
‘step size’ is the difference between the consecutive elements. For example:
>> x = 1:-0.2:0
x =
1.0000 0.8000 0.6000 0.4000 0.2000 0
If the difference between consecutive elements of the row is +1, ‘step size’ can be omitted. For
example,
>> x = 1:5
x =
1 2 3 4 5
For arrays with m rows and n columns, the numbers or elements aij are sorted in different rows and
columns:
Between ‘[‘ and ‘]’ the elements are separated by spaces or commas, and the rows are
separated by a semicolon. The commands are:
or
>> a = [1,2,3;4,5,6;7,8,9]
Between ‘[‘ and ‘]’ where the elements are separated by spaces or commas, and each row
is entered on a new line by using the ‘return’ key. The command now is
>> a = [1 2 3
4 5 6
7 8 9]
a =
1 2 3
4 5 6
7 8 9
Elements of arrays can be indicated by means of their index. In the case of row and column vectors,
one index suffices. This can be used according to the Table 1.5.
Arrays (both matrices and vectors) can be concatenated into new arrays. If the arrays are arranged
in a row, the number of rows in the arrays have to be equal. If the arrays are arranged in column,
the number of columns in the arrays have to be equal. The concatenation of the arrays a = [2 3
4] and b = [6 5] proceeds as follows:
>> [a,b]
ans =
2 3 4 6 5
The operations addition and subtraction are automatically interpreted as array operations. After the
assignments
>> a+b
ans =
7 7 7
>> a-b
ans =
Array operations, such as multiplication ‘*’, division ‘/’ and raising to a power ‘^’, are indicated
by putting a dot ‘.’ in front of the operation sign. In these array operations, the operation is
performed elementwise, e.g. the 1,1-element of a.*b, yields a(1,1)*b(1,1) when a and b are arrays
of appropriate sizes.
Hence
>> a.*b
ans =
6 10 12
>> a./b
ans =
0.1667 0.4000 0.7500
>> a.^b
ans =
1 32 81
1. If in an array operation one of the arrays is a number, this number is interpreted as an array
of which each element equals this number, and of which the size is equal to the size of the
other array.
2. If each element of an array is to be multiplied by a scalar, one does not need to put a dot in
front of the multiplication sign.
Examples:
>> 2.^b
ans =
64 32 16
>> [2 2 2].^b
ans =
>> a./2
ans =
0.5000 1.0000 1.5000
>> 3*a
ans =
3 6 9
Detailed information about these operations can be obtained with the command help arith.
We want to assign the row vector to the variable y. First we make an array with the arguments [0,
0.2, , 1.8, 2].
>> x = 0:0.2:2
x =
Columns 1 through 7
Columns 8 through 11
For making the row of function values, we use array operations. Here, using dots is necessary,
since the function f(x) should be evaluated per element of x.
>> y = x.^3./(1+x.^2)
y =
Columns 1 through 7
Columns 8 through 11
In fact, this boils down to a component wise division of a row of numerators and a row of
denominators.
Relational array operations are operations where arrays are compared elementwise.
the command for finding out which elements in A are larger than corresponding elements in is
given by:
>> A > B
ans =
0 1 1
1 1 0
Entries with a ‘1’ (true) indicate the elements of A that are larger than corresponding elements
of B. Otherwise the entry will be ‘0’ (false). The result is thus an array with Boolean entries. You
can only compare the elements of array and if the arrays and have the same size,
or if one of the arrays is a scalar. For example,
>> A > 2
gives:
Operation Meaning
> greater than
>= greater than or equal to
< lower than
<= lower than or equal to
== equal to
~= not equal to
Relational operations are often used in combination with the function find. Look at the result of
the command help find.
In MATLAB, the mathematical standard functions sin, cos, sqrt, atan, asin, etc.
automatically operate on arrays.
>> a = [1 2 3];
>> sin(a)
ans =
0.8415 0.9093 0.1411
>> sqrt(a)
ans =
1.0000 1.4142 1.7321
Consider the function f(x) = x sin(x). A row of function values can be generated with the following
command:
The result gives the size of A , i.e., the number of rows nr and the number of columns nc. The
function
>> sum(A)
calculates the column sums in a rectangular array A and gives the sums in a row vector. (A column
sum is the sum of the elements of a column.) If A is a row vector, then the sum of the elements
of A is calculated. The function
>> prod(A)
5.5 Transposition
In an array (matrix), the rows and columns can be interchanged. This is called transposition. The
result is called the transposed array. In MATLAB, transposition can be performed with the
function transpose. After the commands
>> a = [1 2 3]
a =
1 2 3
A =
1 2
3 4
5 6
>> transpose(a)
and
>> transpose(A)
ans =
1 3 5
2 4 6
6 Graphs
To draw a graph, you first need to open a graphic screen. This is done with the command:
>> figure
>> plot(v)
where is a row vector containing the numbers until , generates a plot where the points
(1, ), (2, ) until (n, ) are connected by straight lines. The command
>> plot(v,w)
with and two row vectors with the same number of elements, plots the points ( , ),
and connects them by straight lines. The command
>> plot(v,w,x,y)
>> plot(x,y,'r--')
will plot y versus x , with a red dashed line. Type help plot to see other line, marker and color
options.
Suppose that we want to draw the graph of the function on the
interval [0,2Π] consisting of 100 linearly spaced points.
Note that the smoothness of the graph is of course determined by the number of point. The graph
can be plotted by using the following commands:
>> x = 0:2*pi/99:2*pi;
>> y = (sin(x)+2*x)./(1+x.^2);
>> figure
>> plot(x,y)
When drawing a graph, the axes are chosen automatically. You can choose the lengths of the axes
yourself with
which takes care that the graph is drawn in the rectangle XMIN ≤ x ≤ XMAX and
YMIN ≤ y ≤ YMAX.
After each new plot command, the old plot will in general disappear. If you want to draw different
plots with different plot commands in the same figure, you have to give the following command
after the first plot command
>> hold on
restores the state in which every new plot command makes the previous plot disappear.
>> shg
The graphical screen remains the the same until either a new plot command is given or until it is
erased. The command for erasing the graphical screen is
>> clf
The command
>> grid
>> title('title')
puts the title indicated by the string between the quotes above the plot. In the example above, the
title will be the word `title'.
>> text(x,y,'string')
puts the text `string' at the point (x,y) of the last plot.
>> xlabel('text')
>> ylabel('text')
You can use other plot functions in MATLAB as well. The most important are given in Figure 1.1.
You can save a figure by selecting "File \ Save as" and select the required file directory, filename
and file type.
Another option is to use the print command. Type help print for additional information. When
you want to be able to open and modify your figures again in MATLAB, you should save your
figure as a .fig file.
If you have to execute a series of commands repeatedly, it might be better to write the commands
in a so called ‘script file’. The file should have a name with the extension ‘.m’.
As an example, let us consider the drawing of the function f(x) = |x sin(2Πx)| on the interval [0,2]
by using a ‘script file’: Through the menu ‘File \ New \ M-file’ the ‘MATLAB Editor/Debugger’
is opened. Type the following lines:
x = 0:0.1:2;
y = abs(x.*sin(2*pi*x));
plot(x,y)
title('f(x)= |x sin(2 pi x)| on the interval [0,2]')
xlabel('x')
ylabel('f(x)')
axis([0 2 0 2])
shg
Save the file through the menu ‘File \ Save’ under the name ‘picture.m’. If you now give the
command picture in MATLAB, then the graph of f(x) on the interval [0,2] will appear. Another
option to save and run a file written in your editor window is to press the button on top of it.
Be careful, that this will overwrite a possible previous file.
It is better to save the commands that generate a figure than to save the figure itself.
In MATLAB you can also define your own functions. MATLAB assumes by default that all
functions act on arrays. Therefore, you must keep in mind the rules for array operations when
writing your own functions. You can then combine your own functions with MATLAB functions.
A function definition has to be saved in a 'function file', which is a file with the extension `.m'. The
name of the file has to be the same as the name of the function, and should have the extension
`.m'.
Consider the function f(x) = x2 + ex. In MATLAB we will write a function with the same name.
The definition of the function has to be saved in the file ‘f.m’. Through the menu ‘File \ New \ M-
file’ or by typing edit on the command line, the ‘MATLAB Editor/Debugger’ is opened. If you
now type the lines:
function y = f(x)
y = x.^2 + exp(x);
and you save the file under the name ‘f.m’, then within MATLAB the function f(x) is available.
Some comments on the file above are in order.
The first line of the file has to contain the word `function'. The variables used are local; they
will not be available in your 'Workspace'.
If x is an array, then y becomes an array of function values.
The semicolon at the end prevents that at every function evaluation unnecessary output
appears on your screen.
Sometimes it is more convenient to define your function at the command line. MATLAB functions
produced at the command line are called anonymous functions. For example, consider again the
function f(x) = x2 + ex. We can create the anonymous function as follows:
>> f = @(x)(x.^2+exp(x))
Here, f is the name of the function, @ is the function handle, x is the input argument
and x.^2+exp(x) is the function.
Anonymous functions can have multiple input arguments. The general structure of anonymous
functions is name = @(input arguments) (functions).
The anonymous function will be evaluated in the same way as the function m-files. Thus the value
of f(1.2) will be obtained by the command
>> f(1.2)
ans =
4.7601
Very often, results of MATLAB calculations need to be reused elsewhere. The values of variables
can be saved in a `.mat file'. This can be done with the command
which results in all variables in use being saved in the file with the name `filename.mat'. The
extension ‘.mat’ does not necessary need to be given. If only a few variables need to be saved,
these variable should be specified after the file name, e.g. only the variables x and y are saved in
the file filename.mat with the command
A saved `.mat' file can be read into MATLAB with the command load
where the extension ‘.mat’ can be omitted. The saved variables and their values are stored in the
workspace and can now be used again.
Besides loading data stored in `.mat' files, MATLAB is useful for processing data which is
obtained from external sources, e.g., experimental measurements. Typically this data is available
as a plain text file organized into columns. MATLAB can easily handle tab or space-delimited
text.
There is more than one way to read data into MATLAB from an external data file. The simplest,
though least flexible, procedure is to use again the load command to read the entire content of the
file in a single step. The load command requires that the data in the file is organized into a
rectangular array. No column titles are permitted. One useful form of the load command is:
where ‘measurements.txt’ is the name of the file containing the data. The result of this operation
is that the data in `measurements.txt' is stored in a variable called `measurements'. Files with
various extension can be used. Note, that any extension except `.mat' indicates to MATLAB that
Suppose you had a simple ASCII file named `meas_xy.txt' that contained two columns of numbers.
The following MATLAB statements will load this data into the variable ‘meas_xy’, and then copy
it into two vectors, x and y .
After applying these commands, the data stored in column 1 of the text file is stored in the
MATLAB variable x , and the data stored in column 2 of the text file is stored in the MATLAB
variable y. You are now able to process this data with MATLAB.
Another option to import data in MATLAB is to select "File \ Import Data". In the window
opening, you can select your data file. Selecting next in this window, various import options are
accessible. For example, you can choose whether MATLAB should split columns between spaces,
or between commas. Furthermore, you can choose the number of header rows. On the right hand
side of your window, you will see a preview how MATLAB will import the data. If you are
satisfied, select finish.
You are supposed to perform the following exercises in the specified order. Before entering each
of the commands, think about the output on the screen and the result of each exercise.
a)
>> a = 1+2+3+4+5+6
b)
>> b = 1+2+3+4+5+6;
c)
>> b+3
d)
>> 1+2+3+4+5+6
e)
>> c = 10*ans
Enter the array 0:900000 and make sure the output appears in the MATLAB Command Window.
Perform the exercise again and and use the key combination `ctrl-c' quickly. What is the effect?
a) Enter >> a = [2,3,4 and use the `return' key. Finish the exercise.
Define the variables u=[2,3,4] and v=[1 5] and then delete them. Check if the variables are
actually deleted.
>> f = 2
and
>> g = 3 + f
Close MATLAB and start it again. Load the file `try.mat' and see if the variables f and g are
known. Where is the file `try.mat' placed?
Exercise 1.6
Make a row vector that consists of the fifth power of the first 40 natural numbers.
Exercise 1.7
Exercise 1.8
Draw a circle with radius 1 and center (0,0) in a square with -2 < x < 2 and -2 <y <2 . Make sure
that the circle looks round!
HINTS:
First make a list of x -coordinates and a list of y -coordinates. Draw the circle. Change the shape
of the figure by using the command >> axis in different combinations.