You are on page 1of 20

MIDDLE EAST TECHNICAL UNIVERSITY

Introduction to
MATLAB
MATLAB Tutorial 1
Prepared by Başak AKTEKE-ÖZTÜRK

TOL – LABORATORY FOR DESIGN AND OPTIMIZATION


tol.ie.metu.edu.tr
2012-1
1. Getting Started

MATLAB (Matrix Laboratory) is a software package useful for numerical


computations, data analysis, algorithm development, simulation, modelling, and
data visualization.

This document is an introduction to teach undergraduate and graduate students


how to use MATLAB for basic problem solving including both built-in functions and
programming constructs of MATLAB. In this document, you can find how to run
MATLAB, some important commands for managing variables in MATLAB, vector and
matrix handling, plotting graphics, importing, and exporting data. MATLAB is an
interactive software environment with its own computer programming language. A
brief introduction to programming in MATLAB is presented in the next sections.

1.1 Availability in METU Campus

MATLAB is a licenced software accessible at all computer labs in METU campus. The
latest version of MATLAB can be downloaded from the FTP site of METU Computer
Center (ftp://ftp.cc.metu.edu.tr/PackagePrograms/Matlab/) and it runs on the
platforms of MS Windows, HP-UX, Linux, Mac OS.

1.2 How to run, interrupt, and terminate MATLAB?

To run MATLAB in MS Windows platforms, use MATLAB shortcut on the Windows


Start Menu or double click MATLAB icon on your Windows desktop. To run
MATLAB on Linux® platforms, type matlab at the operating system prompt.

When you start MATLAB, there are five embedded windows: Command Window,
Command History and Current Directory, Launch Pad (hidden) and Workspace
Browser (hidden). You can start using MATLAB by issuing your commands on
Command Window.

1
If MATLAB is stuck in a calculation, is taking too long to perform an operation, or
you want to return to the prompt you can interrupt it by typing CTRL+C.

Typing quit or exit terminates MATLAB. Another way of terminating MATLAB is to


select File>Exit menu.

1.3 Getting help

There are several ways to get online help in MATLAB. To get help on a particular
command on which help is available, enter help followed by the name of the
command: help command. There are several arguments passed to the help, like
help general for general purpose MATLAB commands. There is demo command for
demos of several options. Also, lookfor command searches through the help for a
specific string.

2. MATLAB Basics

 In MATLAB, every expression, or variable, has a type associated with it. By default,
numbers are stored as the type double (short for double-precision). The type char
is used to store either single characters (e.g., ‘x’) or strings, which are sequences of
characters (e.g., ‘cat’). Both characters and strings are enclosed in single quotes. The
type logical is used to store true/false values.

 MATLAB supports many types of values, which are called classes. A class is
essentially a combination of a type and the operations that can be performed on
values of that type. Three different classes of MATLAB data are widely used: floating
point numbers, strings, and symbolic expressions.

 MATLAB uses double-precision floating point arithmetic accurate to approximately


15 digits, however, only 5 digits are displayed, by default. To display more digits,
type format long. Then all subsequent numerical output will have 15 digits
displayed. Type format short to return to 5-digit display.

2
>> pi
ans =
3.1416

>> format long


>> pi
ans =
3.141592653589793

>> format short


>> pi
ans =
3.1416

 In a long MATLAB session it may be hard to remember the names and classes of all
the variables you have defined. You can type whos to see a summary of the names
and types of your currently defined variables. This command shows information
about all defined variables, but it does not show the values of the variables.

 To see the value of a variable, simply type the name of the variable on the command
line.

 To clear all defined variables, type clear or clear all. You can also type, for example,
clear x y to clear the variables x and y.

 If you make a mistake in an input line, MATLAB will beep and print an error
message.

 Typing a semicolon at the end of an input line prevents printing of the output of the
MATLAB command.

 The function rand can be used to generate random real numbers; calling it
generates one random real number in the range from 0 to 1.

3
 Built-in constants in MATLAB are: pi, i, inf, NaN (not a number).

 There is no built-in constant for e (2.718), use exp(1).

2.1 Vectors and Matrices in MATLAB

It is possible to deal with vectors (1 dimensional arrays), matrices (2 dimensional


arrays), and higher dimensional arrays easily in MATLAB. A vector in MATLAB is
equivalent to what is called a one-dimensional array in other languages. A matrix is
equivalent to a two-dimensional array. You can enter a vector of any length in
MATLAB by typing a list of numbers, separated by commas or spaces, inside square
brackets. For example,

>> u = [1,6,13,4] % Vector u is defined separated by commas


u=
1 6 13 4

>> v = [2 -3 4 -5 6 -7] % Vector v is defined separated by spaces


v=
2 -3 4 -5 6 -7

>> newv = [u v] % Concatenating vectors


newv =
1 6 13 4 2 -3 4 -5 6 -7

>> u(3) % Extracting the elements of a vector, i.e., u(3)


ans =
13

>> u=[1:5] % Generate a vector of equally-spaced elements with colon operator


u=
1 2 3 4 5

>> u=[1:2:10] % Increment by 2

4
u=
1 3 5 7 9

>> transu = u’ % Get the tranpose of u


transu=
1
3
5
7
9

To type a matrix you must: begin with a square bracket, separate elements in a row
with commas or spaces, use a semicolon to separate rows, end the matrix with
another square bracket :

>> A = [1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9

>> A(2,:) % To publish 2nd row of the a matrix


ans =
456

>> A(:,3) % To publish 3rd column of the a matrix


ans =
3
6
9

MATLAB has several commands that generate special matrices. The commands
zeros(n,m) and ones(n,m) produce n×m matrices of zeros and ones, respectively.
Also, eye(n) represents the n×n identity matrix, rand(n,m) generates a matrix with
all entries random numbers in [0,1].

5
The length(vector) and size(matrix) functions in MATLAB are used to find array
dimensions. The length function returns the number of elements in a vector. The
size function returns the number of rows and columns in a matrix.

>> length (u)


ans =
5

>> size (A)


ans =
3 3

Operations like +, -, *, /, and ^ can be carried out in a matrix sense (according to


the rules of matrix algebra) or elementwise. When elementwise operation is carried
out in MATLAB, a period precedes the operator: .+, . -, . *, . /, and .^ .

2.2 MATLAB Functions

In MATLAB you will use built-in functions as well as functions that you create
yourself. MATLAB has many built-in functions, typing help elfun and/or help
specfun calls up full lists of elementary and special functions. These include sqrt,
cos, sin, tan, log, and, exp.

For the user-defined functions, you can use inline (‘function’,’independent


variable’) command:

>> f = inline('xˆ2 + 2*x + 1', 'x')


f=
Inline function:
f(x) = x^2 + 2*x + 1

>> f(4) % Once the function is defined, you can evaluate it


ans =

6
25

2.3 Symbolic Computation in MATLAB

You can carry out algebraic or symbolic calculations in MATLAB, such as simplifying
polynomials, differentiation with diff function, integration with int function or
solving algebraic equations. To find out about the int function, for example, from the
Command Window:

>> help sym/int

To perform symbolic computations, use syms to declare the variables you plan to
use as symbolic variables. Some of the important functions are: simplify, subs,
solve, diff and int.

>> syms x y

>> (x-y)*(x+y)*(x^2+2*x+1)
ans =
(x + y)*(x - y)*(x^2 + 2*x + 1)

>> f=simplify((x-y)*(x+y)*(x^2+2*x+1)) % to simplify the expression


f=
(x^2 - y^2)*(x + 1)^2

>> subs(f, x, 2) % to substite x=2 in f


ans =
36 - 9*y^2

>> solve(f) % to solve f=0 with respect to x


ans =
y
-1
-1

7
-y

>> f1=diff(f,x) % to differentiate f with respect to x


f1 =
(2*x + 2)*(x^2 - y^2) + 2*x*(x + 1)^2

>> f2=int(f,x) % to integrate f with respect to x


f2 =
x^4/2 - x*y^2 - x^3*(y^2/3 - 1/3) - x^2*y^2 + x^5/5

2.4 Input/Output

It is possible to write programmes that accept input from the user and produce
informative output. Statements that are called input/output statements are used for
these tasks with MATLAB functions input and fprintf.

>> rad = input(‘Enter the radius: ’)


Enter the radius: 5
rad =
5

>>name=input(‘Enter your name: ’) % to enter characters


Enter your name: ‘basak’
Name=
basak

>> fprintf(‘The value of six square is %d\n’,36)


The value of six square is 36

>> fprintf(‘Six square is %3d and the square root of 2 is %6.2f\n’,36,1.47)


Six square is 36 and the square root of 2 is 1.47

The character ‘\n’ at the end of the string is a special character called the newline
character; when it is printed the output moves down to the next line. The %d in

8
fprintf is sometimes called a placeholder; it specifies where the value of the
expression that is after the string is to be printed. The character in the placeholder is
called the conversion character, and it specifies the type of value that is being
printed. A list of the simple placeholders:

%d integers (it actually stands for decimal integer)


%f floats
%c single characters
%s strings

3. MATLAB M-Files

For complicated problems, the simple editing tools provided by the Command
Window are insufficient. A much better approach is to create an M-file which are
ordinary text files containing MATLAB commands with .m extension. You can
create and modify them using any text editor or word processor that is capable of
saving files as plain ASCII text. There are two different kinds of M-files: script M-files
and function M-files.

3.1 Script M-files

The simplest MATLAB programs are called scripts which are stored in M-files. Script
M-files execute a series of MATLAB statements without any input and output
arguments. These script files are interpreted by MATLAB interpreter line by line,
rather than compiled. Therefore, the correct terminology is that these are scripts,
and not programs. The contents of a script can be displayed in the Command
Window using the type command. The script can be executed, or run, by simply
entering the name of the file (without the .m extension).

To create a script, click File, then New, then M-file. A new window will appear called
the Editor. To create a new script, simply type the sequence of statements (notice
that line numbers will appear on the left). When finished, save the file using File and

9
then Save. Make sure that the extension .m is on the filename (this should be the
default). The rules for filenames are the same as for variables (they must start with a
letter, after that there can be letters, digits, or the underscore, etc.). By default,
scripts will be saved in the Work Directory. If you want to save the file in a different
directory, the Current Directory can be changed.

3.2 Function M-files

Function M-files accept input arguments and produce output. Note that it is
appropriate to use inline functions for defining simple functions that can be
expressed in one line. Function M-files are useful for defining functions that require
several commands to compute the output. The first line in a function M-file is called
the function definition line; it defines the function name, as well as the number and
order of input and output arguments:

function [output_parameters] = function_name (input_parameter)

A function is distinguished by the function keyword. MATLAB cannot execute a


function unless it knows where to find its M-file. Make sure that you introduce the
path of your M-file from MATLAB menu File>Set Path.

4. Plotting in MATLAB

There are several plot functions in MATLAB beginning with “ez” that plot symbolic
expressions. For example, the function ezplot will draw a 2-D plot in the x-range
from –2p to 2p, with the expression as the title (in pretty form).

Function ezplot expects a string or a symbolic expression representing the function


to be plotted. The string form notation is ezplot (‘function’,interval) where
specifying interval is optional. For example, to graph x2 + 2x + 1 on the interval −2 to
2 using the string form:

10
>> ezplot (’xˆ2 + 2*x + 1’, [-2 2])

The command plot produces 2D graphics. Before using plot command, define the
interval for the independent variable x and the function of the form y=f(x). Then plot
(x,y) command is called to obtain the figure of f(x) with respect to x:

>> x = 0:0.1:2*pi;
>> y = sin(x);
>> plot (x,y)

>> x = 1:5;
>> y = [0 -2 4 11 3];
>> z = 2:2:10;
>> plot3(x,y,z,‘k*’)
>> grid

Each time you execute a plotting command, MATLAB erases the old plot and draws a
new one. If you want to overlay two or more plots, type hold on. Figures are
displayed in Figure Window which has its own plot editor. You can format your
figure using this editor.

A useful plotting function is subplot, which creates a matrix of plots in the current
Figure Window. Three arguments are passed to it in the form subplot(r,c,n); where r
and c are the dimensions of the matrix and n is the number of the particular plot
within this matrix.

MATLAB has several other plotting functions: fplot(similar to plt),


subplot(multiple plots on the same window), plot3(3D plots), ezplot3(3D plots),
mesh(3D plots), surf(3D plots), contour, and, ezcontour

You can have a title on a graph, label each axis, change the font and font size, set up
the scale for each axis and have a legend for the graph. You can also have multiple
graphs per page.
11
4. Data Exchange

Many applications in engineering and the sciences involve manipulating large data
sets that are stored in external files. MATLAB can easily get data from or send data
to other softwares.

3.1 Between MATLAB and Excel with xlsread and xlswrite


Functions

3.1.1 Excel to MATLAB

MATLAB's function for extracting data from Excel documents is xlsread. Using it is
as simple as this:

[NumericData TextData] = xlsread(FileName,SheetName,CellRange)

where NumericData and TextData contain the numeric and text data read from the
workbook, respectively; and FileName, SheetName and CellRange are the names of
the Excel document, sheet name and cell range from which to read.

3.1.2 MATLAB to Excel

Writing data to Excel documents is also quite simple. Just use xlswrite:

xlswrite(FileName,DataArray,SheetName,CellRange)

where FileName, SheetName and CellRange are the names of the Excel document,
sheet name and cell range to which to write, and DataArray contains the data to be
written.

3.2 Between MATLAB and GAMS with .gdx Files

A GDX file is a file that stores the values of one or more GAMS symbols such as sets,
parameters variables, and equations. A GDX file does not store a model formulation

12
or executable statements. GDX files are binary files that are portable between
different platforms. Reading and writing of GDX files in a GAMS model can be done
during the compile phase or the execution phase. A GDX file can also be written as
the final step of GAMS compile or execute sequence.

3.2.1 GAMS to MATLAB

Three MATLAB routines are important for data exchange between MATLAB and
GAMS, namely 'rgdx', 'wgdx' and 'gams'. The first two are used to read and write
data, respectively, from a GDX file into MATLAB and the third routine will take user
input to execute a gams model from MATLAB and get results back in MATLAB.
Necessary syntax and explanations for GAMS and MATLAB interfacing are available
in the documents related with GDXMRW utilities:
http://www.gams.com/dd/docs/tools/gdxmrw.pdf

3.2.2 MATLAB to GAMS: Using the GDX Facilities in GAMS

Reading and writing of GDX files in a GAMS model can be done during the compile
phase or the execution phase. A GDX file can also be written as the final step of
GAMS compile or execute sequence. For further information:
http://www.gams.com/dd/docs/tools/gdxutils.pdf

Compile phase:

During compilation, we can use dollar control options to specify the gdx file and the
symbols to read or write. Reading during the compilation phase also allows us to
define the elements of a set and the subsequent use of such a set as a domain.
Example (Compile phase reading data example to use the demand data from
an external source): The parameter B is read from the GDX file using the name
'demand', and only those elements that are in the domain J will be used.

Set
j markets / new-york, chicago, topeka / ;

13
Parameter
B(j) demand at market j in cases ;

$GDXIN demanddata.gdx
$LOAD b=demand
$GDXIN

Execution phase:

To read data: execute_load 'filename',id1,id2=gdxid2,..;

To write data: execute_unload 'filename',id1,id2=gdxid,..;

5. Introduction to Programming in Matlab: Relational and


Logical Operators/Functions

Every time you create an M-file, you are writing a computer program using the
MATLAB programming language. A logical is a variable which is assigned to a
relational or logical expression .

>> a = true
a=
1

>> b = false
b=
0

4.1 Relational operators in MATLAB

14
Relational operators are used to compare two arrays of the same size or to compare
an array to a scalar. In the second case, the scalar is compared with all elements of
the array and the result has the same size as the array. A statement that includes a
relational operator is called a logical expression either true or false. If the statement
is true, it is assigned a value of 1, and a value of 0 when it is wrong.

MATLAB's relational operators are

== equal
~= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

Note that a single = is different than double == and denotes assignment and never a
test for equality in MATLAB.

>> A=1:5, B=2.*A-1


A=
12345
B=
13579

>> compAB = A <B


compAB =
01111

>> compAB2= A == B
compAB2 =
10000

15
Logical operators and find command

& (logical and) operator takes two logical expressions and returns true if both
expressions are true, and false otherwise.

| (logical or) operator takes two logical expressions and returns true if either of the
expressions are true, and false only if both expressions are false.

~ (logical not) operator takes only one logical expression and returns the opposite
(negation) of that expression.

Relational and Logical functions in MATLAB: There are many useful logical
functions whose names begin with is. The results of MATLAB's logical operators and
logical functions are logical arrays of 0s and 1s.

isequal (A,B): To test whether arrays A and B are equal, that is, of the same size
with identical elements, the expression can be used:
>> isequal (A,B)
ans=
0

isempty: test for empty array


isequal: test if arrays are equal
isfinite: detect finite array elements
isinf: detect infinite array elements
isinteger: test for integer array
issorted: test for sorted vector

Other important logical functions are: ischar, isequalwithequalnans, isfloat, islogical,


isnan, isnumeric, isreal, isscalar, isvector.

Other important logical functions are all, any, and, find for specifying nonzero
elements of arrays:

16
all returns true if all elements of vector is nonzero
any returns true if any element of vector is nonzero
find command also can be used to extract the nonzero elements of an array:

>> x = [ -3 1 0 -inf OJ ;

>> f = find(x)
f=
124

>> x(f)
ans=
-3 1 –Inf

>> x(find(isfinite(x)))
ans=
-3
1
0
0

Remark (Operator Precedence)

Arithmetic, relational, and logical operators can all be combined in mathematical


expressions. When an expression has such a combination, the result depends on the
order in which the operations are carried out. The following is the order used by
MATLAB:

(highest) Parenthese
Exponentiation
Logical NOT (~)
Multiplication, division

17
Addition, subtraction
Relational operators (>,<,>=,<=,==,~=)
Logical AND (&)
(lowest) Logical OR (|)

4.2 Flow Control

MATLAB supports the basic flow control constructs found in most high level
programming languages. The syntax is a hybrid of C and Fortran.

If Constructs
if test
do something
end

MATLAB supports these variants of the if construct


if ... end
if ... else ... end
if ... elseif ... else ... end

While Constructs
while test
do something
end

where test is a logical expression. The do something block of code is repeated until
the test in the while statement becomes false.

For constructs: The for construct is used to create a loop, usually over a fixed range
of steps

18
for index = start:increment:stop
do something
end

6. Useful Readings:

1. Brian R. Hunt Ronald L. Lipsman Jonathan M. Rosenberg, A Guide to MATLAB for


Beginners and Experienced Users, 2001.

2. Desmond J. Higham, Nicholas J. Higham, MATLAB Guide, 2005.

3. Micheal G. Kay, Basic Concepts in MATLAB, January 2009.

19

You might also like