You are on page 1of 15

MATLAB® Summary Note

Woo Kyun Kim


University of Cincinnati

1. Calculator Mode

1.1. Three primary windows and calculator mode

(1) There are three primary windows used in MATLAB.


• Command window: used to enter commands in the calculator mode (also called interactive mode)
• Graphics window: used to display plots and graphics
• Edit window: used to create and edit m-files for programming
(2) In the command window, you can see the prompt >>, which tells you that it is ready to accept a com-
mand. You type in a command and hit the enter key , then MATLAB will show you the answer and
the prompt will appear in the next line waiting for your next command. So, it works line by line in a
sequential fashion.
>> 100-50
ans =
50
>> 100*5
ans =
500
(3) Each answer is displayed and is stored in variable ans.
(4) ans is a variable so you can use it in the next command. But, note that ans is updated with the answer
from the new command.
>> 100-50
ans =
50
>> ans*10
ans =
500
(5) If semicolon (;) is added at the end of a command, its outcome is not displayed.
>> 100-50;
>>

1
(6) Several commands can be listed in one line, separated by either comma (,) or semicolon (;).
>> 1+1,2+2;3+3,4+4;
ans =
2
ans =
6

(7) A long command can be placed in multiple lines using ellipsis (...).
>> 100*(1+...
1)
ans =
200

(8) Displaying the results can be controlled using format command (e.g. format short vs. format
long, format compact vs. format loose, etc.). See the attached table uploaded in Canvas.

(9) Complex numbers are represented by either i or j. For display, only i is used.
>> 1+2*i
ans =
1.0000 + 2.0000i
>> 1+2*j
ans =
1.0000 + 2.0000i

(10) Using the key, the previously typed-in commands can be accessed.

(11) clc command clears the screen.


>> clc

(12) help and lookfor commands are used to find additional information about MATLAB functionalities.
>> help log
>> lookfor logarithm

1.2. Variables and assignment

(1) Using variables is a very convenient way to perform mathematical operations. In programming a vari-
able is associated with one particular location of memory block for the reference and manipulation of
the data that it holds.

(2) In MATLAB, unlike other programming languages like C++ and FORTRAN, variables can be used with-
out declaration of types of the data that they can store once assigned a value of any data type.
>> x=1
x =

2
1
>> y=1+2*i
y =
1.0000 + 2.0000i

(3) Variables and their values are shown in the workspace window.

(4) A MATLAB variable name starts with a letter, followed by letters, digits, or underscore. MATLAB variable
names are case-sensitive so a and A are regarded as different variables.
>> a=1
a =
1
>> A=2
A =
2

(5) A variable can be reassigned with different types of values.


>> x=1
x =
1
>> x=1+2*i
x =
1.0000 + 2.0000i

(6) MATLAB has some internally-defined symbols to hold constants such as pi.
>> pi
ans =
3.1416

(7) Variables can be looked up using who and whos commands.


>> who
>> whos

(8) clear command removes all user-defined variables.


>> clear

1.3. Arrays

(1) In programming an array is associated with a collection of several contiguous memory blocks of fixed
size holding the same data type. Each memory block of an array is referred to as its element. Arrays
are very convenient when dealing with many variables of the similar kind. For example, for the x
coordinates of 100 points, it is more convenient to work with one array x of size 100 rather than having
100 variables of different names.

3
(2) The dimension of an array is the number of indexes needed to select an element of the array. It is
closely related to the arrangement of memory blocks of an array. For example, if the memory blocks are
arranged in one line, the corresponding array is one-dimensional (1-D) and a single index is sufficient
to refer to a specific element of it. Also, if the memory blocks are arranged in a rectangular plane, the
corresponding array is two-dimensional (2-D) and two indexes are required to specify an element.

(3) All MATLAB variables are 2-dimensional arrays. A variable holding scalar values is a 1 × 1 array.

(4) MATLAB has various ways to define array variables.

• Direct listing of elements.


>> a=[1 2 3 4 5]
a =
1 2 3 4 5
>> b=[1 2 3 4 5]′
b =
1
2
3
4
5
Here, single quotation (′ ) is the transpose operator.
>> c=[1 2; 3 4; 5 6]
c =
1 2
3 4
5 6
>> d=[ [1 2 3]′ [4 5 6]′ [7 8 9]′ ]
d =
1 4 7
2 5 8
3 6 9
• Using colon (:) operator.
>> 1:5
ans =
1 2 3 4 5
>> 1:2:10
ans =
1 3 5 7 9
>> 10:-2:1
ans =
10 8 6 4 2

4
• Using MATLAB functions.
zeros(m,n) creates an m × n array filled with 0.
>> zeros(2,3)
ans =
0 0 0
0 0 0
ones(m,n) creates an m × n array filled with 1.
>> ones(2,3)
ans =
1 1 1
1 1 1
linspace(x1, x2, n) creates an n × 1 array (row vector) of n evenly spaced points between x1 and
x2.
>> linspace(1,10,10)
ans =
1 2 3 4 5 6 7 8 9 10
logspace(x1, x2, n) creates an n × 1 array filled with 10 x1 , ..., 10 x2 where the powers are evenly
spaced points between x1 and x2.
>> logspace(-1,1,3)
ans =
0.1000 1.0000 10.0000

(5) An (m,n) element of array A can be accessed by A(m,n). A part of array can also be accessed by using
colon (:) operator, e.g.,
>> d=[ [1 2 3]′ [4 5 6]′ [7 8 9]′ ]
d =
1 4 7
2 5 8
3 6 9
>> d(2,3)
ans =
8
>> d(:,1)
ans =
1
2
3
>> d(2,1:2)
ans =
2 5

5
1.4. Operators and built-in functions

(1) There are two types of MATLAB operations.

• Array operation: the operation is applied in the element-by-element fashion. These types of opera-
tions can be defined between arrays of the same sizes.
• Matrix operation: the operation follows the rules of matrix operation defined in linear algebra.

(2) Some matrix operations in linear algebra are defined in the element-by-element fashion so there is no
distinction between array operation and matrix operation, e.g., addition, subtraction, scalar multiplica-
tion, etc.
>> a=[2 2 2; 2 2 2]
a =
2 2 2
2 2 2
>> b=[1 1 1; 1 1 1]
b =
1 1 1
1 1 1
>> a+b
ans =
3 3 3
3 3 3
>> a-b
ans =
1 1 1
1 1 1
>> 5*b
ans =
5 5 5
5 5 5

(3) Adding, subtracting, multiplying, and dividing by a scalar constant are always carried out element-by-
element.
>> a=[2 2 2; 4 4 4]
a =
2 2 2
4 4 4
>> a+1
ans =

6
3 3 3
5 5 5
>> 2+a
ans =
4 4 4
6 6 6
>> a-1
ans =
1 1 1
3 3 3
>> 1-a
ans =
-1 -1 -1
-3 -3 -3
>> a*2
ans =
4 4 4
8 8 8
>> 3*a
ans =
6 6 6
12 12 12
>> a/2
ans =
1 1 1
2 2 2

(4) In cases where matrix operations are not defined in the element-by-element fashion, MATLAB provides
two different operations. For example, in linear algebra the multiplication of two matrices A and B,
A × B, can be defined only when the number of columns of A is the same as the number of rows of
B such that, when C = A × B and n is the number of columns of A, Ci j = ∑nk=1 Aik Bk j (we will revisit
matrix operations in Ch. 8). This operation is carried out using * operator, e.g.,
>> A=[1 2 3; 4 5 6]
A =
1 2 3
4 5 6
>> B=[1 2; 3 4; 5 6]
B =

7
1 2
3 4
5 6
>> A*B
ans =
22 28
49 64
Note that A*B is valid only when the number of columns of A is equal to the number of rows of B.
Otherwise, an error message will show up.
Alternatively, the multiplication of two arrays can be carried out element by element using .* operator,
e.g.,
>> A=[1 2 3; 4 5 6]
A =
1 2 3
4 5 6
>> C=[2 2 2; 2 2 2]
C =
2 2 2
2 2 2
>> A.*C
ans =
2 4 6
8 10 12
Note that A.*B is valid only when A and B are of the same size. Otherwise, an error message will show
up.
Similarly, A^2 (=A*A) is valid only for square arrays (the same number of rows and columns) while
A.^2 can be carried out for any arrays, e.g.,
>> A=[1 2; 3 4]
A =
1 2
3 4
>> A^2
ans =
7 10
15 22
>> A=[1 2 3; 4 5 6]
A =

8
1 2 3
4 5 6
>> A.^2
ans =
1 4 9
16 25 36
Element-by-element array division is carried out using ./.
>> A=[4 6 8; 10 12 14]
A =
4 6 8
10 12 14
>> B=[2 2 2; 2 2 2]
B =
2 2 2
2 2 2
>> A./B
ans =
2 3 4
5 6 7
MATLAB has two matrix divisions / and \. A/B is valid when A and B have the same number of columns
and returns x such that x*A=B while A\B is valid when A and B have the same number of rows and
returns x such that A*x=B.

(5) Most MATLAB built-in math functions such as sin(), cos(), tan(), sqrt(), log(), exp(), round(),
ceil(), floor(), etc. operate as in the array operation, e.g.,
>> x=[1 4 9 16 25]
x =
1 4 9 16 25
>> sqrt(x)
ans =
1 2 3 4 5

(6) There are some exceptions, e.g., sqrtm(A) is an array whose square is equal to A so it is operatable
only for square matrices while sqrt(A) operates on each element of A so can be used with arrays of
any size.
>> A=[3 8; 4 11]
A =
3 8
4 11

9
>> sqrtm(A)
ans =
1.0000 2.0000
1.0000 3.0000
(7) There are also many useful built-in functions extracting the array-level information such as length(),
size(), sum(), min(), max(), sort(), etc. For example,
>> x=[1 4 9 16 25]
x =
1 4 9 16 25
>> length(x)
ans =
5
>> A=[1 2 3; 4 5 6]
A =
1 2 3
4 5 6
>> size(A)
ans =
3 2
>> size(A,1)
ans =
3
>> size(A,2)
ans =
2
Thus, use length() for row vectors (1 × n) or column vectors (m × 1) and size() for others.

2. Graphics

(1) There are two main ways of plotting graphs.


• plot(x,y): plotting with two arrays of x and y. For example,
>> x=0:0.1:2*pi;
>> y=sin(x);
>> plot(x,y)
or
>> y2=cos(x);
>> plot(x,y,x,y2)

10
• fplot(f, [a b]): plotting with a function f in the range of [a, b]. For example,
>> fplot(@(x)sin(x),[0 2*pi])
or
>> fplot(@sin,[0 2*pi])

(2) Each plotting command erases the previous graphic and draws a new one unless hold on is used. See
the difference between

>> fplot(@sin,[0 2*pi])


>> fplot(@cos,[0 2*pi])
and
>> fplot(@sin,[0 2*pi])
>> hold on
>> fplot(@cos,[0 2*pi])

(3) Graphs can be more featured using

• title(‘...’): adds a title to the plot.


• xlabel(‘...’): adds a label to the x axis.
• ylabel(‘...’): adds a label to the y axis.
• grid: displays grid lines.
• xlim([a b]): sets the x axis limits.
• ylim([a b]): sets the y axis limits.
• axis([a b c d]): sets both the x axis and y axis limits.
• legend(label1, label2, ...): creates a legend with descriptions of each data.
etc.

(4) Curve colors, types, thickness, etc. and marker types, colors, size, etc. can also be controlled. See the
attached table for available options.

>> plot(x,y,‘ro-’)
>> plot(x,y,‘LineWidth’,2)
>> plot(x,y,‘MarkerSize’,10)
>> plot(x,y,‘MarkerEdgeColor’,‘b’)
>> plot(x,y,‘MarkerFaceColor’,‘m’)

(5) Other plotting functions are available such as semilogx(), semilogy(), loglog(), polar(), etc.
Use help command for details.

(6) Using subplot(m,n,p) creates a matrix of multiple graphs, i.e., a subsequent plot command places
a graph at pth location in the m × n matrix.

(7) clf command clears the graphics window.


>> clf

11
3. M-files

An M-file is a simple text file consisting of several MATLAB command lines and having a name with the
extension ‘.m’. They can be created and edited in the edit window, but, since they are just text files, any text
file editor like Notepad in Windows can also be used for editing. There are two types of m-files; (i) script
m-files and (ii) function m-files.

3.1. Script m-files

(1) An script m-file contains a series of MATLAB commands that are saved in a single text file. It is like a
source code in other programming languages.

(2) To execute a script m-file, either (i) type the file name without .m in the command line and press the
enter key (the file should be in a folder saved in MATLAB search path. Folders can be added to
MATLAB search path using the Set Path button.) or (ii) click the Run button while the file is open in
the edit window.

(3) Variables defined in the command line and script m-files all appear in the workspace and can be referred
to interchangeably, i.e., the variables defined in a script m-file can be accessed in the command line once
the file is executed and vice versa. In other words, the variables defined in scripts and in the command
line have the same scope.

(4) Any statement following % is regarded as a comment so is not executed.

(5) M-files can get user-providing inputs using input() and write outcomes using disp() or fprintf().

• x=input(prompt) displays the text in prompt and waits for the user to input a value and press the
enter key. The value provided by the user is assigned to the variable x.
• disp(‘...’) prints the text ... and disp(x) displays the value in variable x.
• fprintf(‘...’, x, y, ...) provides a means to write a text with formatted output of variables.
See the attached table for available options.

(6) Structural programming can be implemented as:

• Conditional branching:
if condition
statement
end

if condition1
statement1
elseif condition2
statement1
.
.
.
else condition3
statement3
end

12
switch variable
case value1
statement1
case value2
statement2
.
.
.
otherwise
statement3
end

Conditions are obtained using logical operations such as ∼ (logical negation), | (logical or), & (logical
and), ==, ∼=, >, <, >=, <=, etc.

• Loops:
for i=start:increment:end
statement
end

while condition
statement
end

while (1)
statement1
if condition,break,end
statement2
end
(7) Other useful commands: break, tic/toc, pause/pause(n), error(‘...’).

3.2. Function m-files

(1) In programming a function is a set of commands grouped together to perform a specific task. Usually a
function is passed with arguments and returns outputs that are computed internally.
(2) MATLAB function format

function [outvar1 outvar2 ...]=funcname(inarg1, inarg2, ...)


% help comments
% ...
statement
end
All the comment lines are displayed by help funcname and the first help comment (H1 line) is
searched by lookfor.

13
(3) The scope of a variable is the area of the program where the variable can be accessed. It can be thought
of a playground of variables. Variables defined in one scope cannot be accessed in a different scope.

• Variables defined in the command line and script m-files have the same scope of the workspace so
they can be interchangeably accessed.
• However, variables defined in a function m-file have the scope confined within the function so they
cannot be accessed from the outside of the function including the workspace and other functions.
They are called local variables.
• Functions do not have access to those variables in the workspace so their values must be passed as
arguments to a function.
• Using global command, variables can be accessed both in the workspace and in functions.

(4) A function may be called with a smaller number of arguments than it has at the definition. For example,

function y=funcname(x1, x2, x3)


% ...
switch nargin
case 0
x1=1;x2=2;x3=3;
case 1
x2=2;x3=3;
case 2
x3=3;
end
.
.
.
statement
.
.
.
end
end

(5) A function can be defined in the command line, called anonymous function, e.g.,
f1=@(x)5*sin(x/7) or f2=@(x,y)x*y+cos(3*x-6*y).

(6) Functions can be passed to another function as arguments.

function y=funcname1(f,...)
f(x) f is a function of one variable.
end

function z=funcname2(f,...)
f(x,y) f is a function of two variables.
end

14
function z=funcname3(f,...,varargin)
f(x,varargin{:}) f is a function of multiple variables, but only one argument x is regarded as a
free variable and the other arguments are passed with values.
end
funcname3 can be called as
t=funcname3(@(x)f(x,10),...)

15

You might also like