0% found this document useful (0 votes)
56 views

Basic Concepts in MATLAB: 1.1 Performance Objectives

This document provides an overview of basic concepts in MATLAB, including: - Using MATLAB to perform matrix calculations, save/load data from files, and create simple plots. - The MATLAB environment and command line interface for executing expressions and functions. - How to create and manipulate arrays, matrices, vectors, including common functions like rand, zeros, ones, eye for generating structured arrays. - Saving and loading variables to .mat files, and selecting/indexing array elements using parentheses and colon operators.

Uploaded by

Muhammad Naveed
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Basic Concepts in MATLAB: 1.1 Performance Objectives

This document provides an overview of basic concepts in MATLAB, including: - Using MATLAB to perform matrix calculations, save/load data from files, and create simple plots. - The MATLAB environment and command line interface for executing expressions and functions. - How to create and manipulate arrays, matrices, vectors, including common functions like rand, zeros, ones, eye for generating structured arrays. - Saving and loading variables to .mat files, and selecting/indexing array elements using parentheses and colon operators.

Uploaded by

Muhammad Naveed
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Data Communication & Networks

Department of Computer Systems & Software Engineering


Mehran University of Engineering & Technology, Jamshoro, Pakistan
Spread Spectrum Communications
Zero Lab

Basic concepts in MATLAB


1.1 Performance Objectives
After this lab, you should be able to:
 Use MATLAB to do simple matrix calculations
 Be able to save data to a file and load matrices from file.
 You will know some of the capabilities of the MATLAB package and will be familiar
with the MATLAB help function.
 You will know how to draw simple plots using MATLAB.
1.2 Equipments Required
 Pentium PC with windows 98/2000/XP
 MATLAB 5.3 or latest with Signal processing and Neural Network Toolbox
1.3 Discussion

1.3.1 The MATLAB Environment specialized topics like fuzzy logic, neural
networks, signal processing, etc. It can be
used in two different ways: as a traditional
programming environment and as an
After launching MATLAB (Version 7,
interactive calculator. In calculator mode,
Release 14), a multipanel window appears
the built-in and toolbox function provide a
containing Command Window,
convenient means of performing one-off
Workspace, Current Directory, and
calculations and graphical plotting; in
Command History panels, among others.
programming mode, it provides a
This, along with windows for the
programming environment (editor,
Editor/Debugger, Array Editor, and Help
debugger, and profiler) that enables the
Browser that can be invoked as needed, is
user to write their own functions and
the MATLAB environment.
scripts.

MATLAB has an extensive set of built-in


Expressions consisting of operators and
functions as well as additional toolboxes
functions that operate on variables are
that consist of functions related to more
executed at the command-line prompt >>

Institute of information & Communication Technology (IICT), MUET


in the Command Window. All of the Arrays can be created on command line as
variables that are created are stored in the follows:
workspace and are visible in the
Workspace panel.
>> n=1

n =
Information about any function or toolbox
is available via the command-line help 1
function (or from the Help Browser
launched from the Help menu):
>> a=[1 2 3]

a =
>> help sum
1 2 3
In MATLAB, everything that can be done
using the GUI interface can also be
accomplished using a command-line
>> M = [1 2 3; 3 2 1]
equivalent. The command-line equivalent
is useful because it can be placed into M =
scripts that can be executed automatically.
1 2 3

3 2 1
1.3.2. Creating Arrays

In MATLAB, the case of a variable matters;


The basic data structure in MATLAB is the
e.g., the arrays a and M are different
two-dimensional array. Array variables can
variables.
be scalars, vectors, or matrices:
To recall the last command executed,
 Scalar n = 1 is represented as 1 × 1
press the up-arrow key (↑). To suppress
array
the output from a command, end an
 Vector a = [1 2 3] is a 1 × 3 array expression with a semicolon (;):

M= 1 2 3
 Matrix
[
3 2 1 ] is a 2 ×
M = [1 2 3; 3 2 1];

3 array.
An empty array is considered a 0 × 0 1
matrix:

>> a=zeros(1,5)
>> a = [] a =
a = 0 0 0 0 0
[]

The rand function generates random


The following operators and functions can numbers between 0 and 1. (Each time it is
be used to automatically create basic run, it generates different numbers.)
structured arrays:

>> a=rand(1,3)
>> a = 1:5 a =
a = 0.9501 0.2311 0.6068

1 2 3 4 5 >> b=rand(1,3)

b =
>> a = 10:-2:1 0.4860 0.8913 0.7621
a =

10 8 6 4 2
A random permutation of the integers 1 to
n can be generated using the
randperm(n) function:
>> a=ones(5,1)

a =
>> randperm(5)
1

1
ans =
1
2 4 1 5 3
1
The variables currently in the workspace
are visible in the Workspace panel, or
By default the rand command generates through the whos command:
number between interval 0 and 1. To
create a random number between interval
a and b, we can use following command.
>> whos
For example,

Name Size Bytes Class


>> a=1; b=5;
M 2x3 48 double array
>> a+(b-a)*rand(1,3);
a 1x3 24 double array

ans 3x3 72 double array


This will generate a 1 × 3 matrix with
numbers between 1 and 5. b 1x3 24 double array

n 1x1 8 double array

To create a 3 × 3 identity matrix:


Grand total is 22 elements using
176 bytes

>> eye(3)

ans =
To save arrays M and a to a file:
1 0 0

0 1 0
>> save myvar M a
0 0 1

Data files in MATLAB have the extension


The variable ans is used as a default .mat, so the file myvar.mat would be saved
name for any expression that is not in the current directory (see Current
assigned to a variable. Directory panel). To remove the variables
from the workspace:

1.3.3. Saving and Loading variables


>> clear
>> M(:,:)

Now again type whos and you will get


nothing as all the variables are cleared ans =

1 2 3

>> whos 3 2 1

To restore the variables: >> M(1,2)

>> load myvar ans =

Data files can also be saved and loaded


using the File menu. >> M(1,:)

1.3.4. Selecting Array Elements ans =

1 2 3

In MATLAB, index arrays inside of


parenthesis are used to select elements of
an array. The colon operator is used to >> M(:,1)
select an entire row or column.

ans =

>> M 1

M =

1 2 3 >> M(:,[1 3])

3 2 1

ans =
1 3 3

3 1 1

The vector [1 3] is an index array, where To select the elements along the main
each element corresponds to a column diagonal:
index number of the original matrix M.

>> diag(B)
The keyword end can be used to indicate ans =
the last row or column:
3 0

0 1
>> M(:,end)

ans =
If let’s suppose C is an square matrix
3
C= 1 2 ,
1 [ ]
3 4 then

>> M(:,end-1)
>> C = [1 2;3 4]

C =
ans =
1 2
2
3 4
2

>> diag(C)
The selected portion of the one array can
be assigned to a new array: ans =

4
>> B=M(:,3,end)

B =
1.3.5. Changing and Deleting Array >> a([1 3])=[7 8]
Elements
a =

7 6 8 4 5
In calculator mode, the easiest way to
change the elements of an array is to
double click on the array’s name in the >> M(1,2)=100
Workspace panel to launch the Array M =
Editor, which allows manual editing of the
array. (The editor can also be used to 1 100 3
create an array by first generating an array
3 2 1
of zeros at the command line and using the
editor to fill in the nonzero values of the
array.)
To delete selected elements of a vector:

In programming mode, elements can be


changed by selecting a portion of an array >> a(3)=[]
as the left-hand-side target of an
a =
assignment statement:
7 6 4 5

>> a=1:5
>> a([1 4])=[]
a =
a =
1 2 3 4 5
6 4

>> a(2)=6

a = A row or column of a matrix can be


deleted by assigning it to an empty array:
1 6 3 4 5

>> a([1 3])=0


>> M(:,2)=[]
a =
M =
0 6 0 4 5
1 3
3 1 3 2 1

1 2 3
1.3.6. Manipulating Arrays

>> [M B] (Concatenate Matrices)


The following operators and functions can ans =
be used to manipulate arrays:
1 2 3 3

3 2 1 1
>> M = [1 2 3; 3 2 1]

M =
>> [M [10 20]'; 30:10:60]
1 2 3
ans =
3 2 1
1 2 3 10

3 2 1 20
>> M' (Transpose)
30 40 50 60
ans =

1 3
>>M(:) (Convert matrix to column vector)
2 2
ans =
3 1
1

3
>> fliplr(M) (flip left/right)
2
ans =
2
3 2 1
3
1 2 3
1

>> flipud(M) (flip up/down)


>> M=M(:)' (Convert matrix to row
ans = vector)
M = Multiplication
1 3 2 2 3 1

Matrices are multiplied together in two


>>M=reshape(M,2,3) (Convert back to different ways: element-by-element
matrix) multiplication, indicated by the use of a
dot (.) along with the operator, and matrix
multiplication, where the inner dimensions
M = of the matrices must be the same; i.e.,

1 2 3

3 2 1 Element-by-element multiplication
Mm×n . *Bm×n = Cm×n

1.3.7. Multiplication and Addition Matrix multiplication


Mm×n . *Bm×p = Cm×p

Scalars >> C = M.*B

A scalar can be added to or multiplied with C =


each element of an array; e.g., 2 8 18

18 8 2
>> 2 + M

ans = >> M*B


3 4 5 ??? Error using ==> *
5 4 3 Inner matrix dimensions must
agree.

>> B = 2*M
>> C = M * B'
B =
C =
2 4 6
28 20
6 4 2
20 28
Matrices are added together in MATLAB
element by element; thus, each matrix
>> C = M' * B
must be the same size; i.e.,
C =
Addition: Mm×n + Bm×n = Cm×n
20 16 12

16 16 16
>> C = M + B
12 16 20
C =

3 6 9
>> a = 1:3
9 6 3
a =

1 2 3
To add vector a to each row of M, a can be
converted into a matrix with the same
>> a * a' dimensions as M. This can be
accomplished in several different ways:
ans =

14
>>ones(2,1)*a (Matrix multiplication)

>> M * a' ans =

ans = 1 2 3

14 1 2 3

10
>> ones(2,1) * a + M

ans =
Division (./) and power (.^) operators can
also be preformed element by element. 2 4 6

4 4 4

Addition
>> a(ones(1,2),:) (Tony’s trick)
ans = 15

1 2 3

1 2 3 >> cumsum(a) (cumulative summation)

ans =

>> repmat(a,2,1) (Replicate array) 1 3 6 10 15

ans = By default, MATLAB is column oriented;


1 2 3 thus, for matrices, summation is
performed along each column (the 1 st
1 2 3 dimension) unless summation along each
row (the 2nd dimension) is explicitly
specified:
Using repmat is fastest approach when a
is a scalar, while Tony’s Trick is not
possible if a does not yet exist and is being >> M
created in the expression for the first time.
M =

1 2 3
Summation 3 2 1

The elements of a single array can be


added together using the sum and cumsum
>> sum(M)
functions:
ans =

4 4 4
>> a = 1:5

a =
>> sum(M,2) (sum along rows)
1 2 3 4 5
ans =

6
>> sum(a) (Array summation)
6
ans =
>> sum(M,1) (sum along columns) 1 3 4

ans =
1.3.8. Functions and Scripts
4 4 4

>> sum(sum(M)) (sum entire matrix) Functions and scripts in MATLAB are just
text files with a .m extension. User-defined
ans = functions can be used to extend the
capabilities of MATLAB beyond its basic
12
functions. A user-defined function is
treated just like any other function. Scripts
are sequences of expressions that are
Forcing column summation: Even if the automatically executed instead of being
default column summation is desired, it is manually executed one at a time at the
useful (in programming mode) to explicitly command-line. A script uses variables in
specify this in case the matrix has only a the (base) workspace, while each function
single row, in which case it would be has its own (local) workspace for its
treated as a vector and sum to a single variables isolated from other workspaces.
scalar value (an error): Functions communicate only through their
input and output arguments. A function is
distinguished from a script by placing the
keyword function as the first term of the
>> M=M(1,:)(Convert M to singlerow
matrix)
first line in the file.

M =

1 3 4 Although developing a set of functions to


solve a particular problem is at the heart of
using MATLAB in the programming mode,
>> sum(M) (Incorrect) the easiest way to create a function is to
do it in an incremental, calculator mode by
ans = writing each line at the command-line,
executing it, and, if it works, copying it to
8
the function’s text file.

>> sum(M, 1) (Correct)

ans =
The best way to start is to create some
example data for which you know the
correct answer:

>> x = [3 1];

>> P = [1 1; 6 1; 6 5]

P =

1 1

6 1

Figure 1.1: Calculation of Euclidean distance 6 5

The first step is to subtract x from each


row in P:
Example 1.1

>> ones(3,1) * x
Given a 2-D point x and m other 2-D points ans =
in P, create a function mydist.m to
determine the Euclidean (i.e., straight-line) 3 1
distance d from x to each of the m points
3 1
in P:
3 1

p 1,1 p1,2
x=[ x 1 x 2 ], P= ⋮
[ ] ⋮
pm , 1 p m ,2
>> ones(3,1)*x - P

ans =

2 0

√( x − p )2 + ( x2 − p1,2 ) 2

[ ]
1 1,1 -3 0
d= ⋮ -3 -4
2 2
√( x − p
1 m,1 ) + ( x 2 − pm , 2 )
Square each element of the result: The M-File Editor can be used to create the
text file for the function mydist. Either
select New, M-File from the File menu, or
>>(ones(3,1)*x - P) .^ 2

ans =
>> edit mydist
4 0

9 0

9 16

Add the elements in each row:

>> sum((ones(3,1)*x - P).^2, 2)

ans =

25

Figure 1.2: Snap of matlab m-file editor

Then take the square root and assign the


result to d:
where the editor should appear. Type the
following two lines (adding a semicolon to
the end of the command-line expression to
>>d=sqrt(sum((ones(3,1)*x-P).^2,2))
suppress output from inside the function):
d =

2
function d = mydist(x,P)
3
d=sqrt(sum((ones(3,1)*x-P).^2,2));
5
Save the file, then check to see if MATLAB The only thing “hard-coded” in the
can find the file by using the type function is m. The size function can be
command to print the function at the used inside the function to determine the
command line, and then check to see that number of rows (dimension 1) or columns
it works as desired: (dimension 2) in P:

>> type mydist >> m = size(P,1)

m =

function d = mydist(x,P) 3

d=sqrt(sum((ones(3,1)*x-P).^2,2));

d = mydist(x,P) >> n = size(P,2)

d = n =

2 2

3 The last thing that should be added to the


5 function is some help information. The
entire first block of contiguous comment
lines in a function is returned when the
help command is executed for the
As it is written, the function will work for function. Comment lines are indicated by
points of any dimension, not just 2-D percent sign (%).
points. For n-dimensional points, x would
be a n-element vector and P a m × n
matrix; e.g., for 4-D points:
To get help:

>> d = mydist([x x],[P P])


>> help mydist
d =

2.8284
MYDIST Euclidean distance from x
4.2426 to P.

7.0711

d = mydist(x,P)
x= n-element vector single point >> a > 0 (Greater than)

P= m x n matrix of n points ans =

d= m-element vector, where d(i) 1 0 0 1 0


= distance from x to P(i,:)

>> a == 7 (Equal to)


The function mydist can now be used
ans =
inside of any expression; e.g.,
0 0 0 1 0

totalDistance = sum(mydist(x,P))
>> a ~= 0 (Not equal to)
totalDistance =
ans =
10
1 0 1 1 0

If other people will be using your function,


it is a good idea to include some error >> (a >= 0) & (a <= 4) (Logical
checking to make sure the values input to AND)
the function are correct; e.g., checking to
ans =
make sure the points in x and P have the
same dimension. 1 1 0 0 1
1.3.9. Logical Expressions

>> (a < 0) | (a > 4) (Logical


A logical array of 1 (true) and 0 (false) OR)
values is returned as a result of applying ans =
logical operators to arrays; e.g.,
0 0 1 1 0

>> a = [4 0 -2 7 0]
>> ~((a < 0)|(a > 4)) (Logical
a = NOT)
4 0 -2 7 0 ans =

1 1 0 0 1
Unlike a regular matrix, a cell array can be
used to store rows of different lengths:
A logical array can be used just like an
index array to select

and change the elements of an array; e.g., >> c = {[10 20 30],[40],[50 60]}

c =

>> a(a > 0) [1x3 double] [40] [1x2 double]

ans =

4 7 The individual elements in the cell array


are each a row vector that can be accessed
as follows:
>> a(a == 7) = 8

a =
>> c{1}
4 0 -2 8 0
ans =

1 2 3
>> a(a ~= 0) = a(a ~= 0) + 1

a =
To access the elements within each row:
5 0 -1 9 0

1.3.10. Cell Arrays, Structures, and N- >> c{1}(1)


D Arrays
ans =

10
Cell Arrays

A cell array is a generalization of the basic To add an element to the end of the first
array in MATLAB that can have as its row:
elements any type of MATLAB data
structure. Curly braces, { }, are used to
distinguish a cell array from a basic array.
>> c{1}(end+1) = 35

c =
[1x4 double] [40] [1x2 double] Some functions can accept a cell array as
input:
>> s = sort(s)
>> c{1}
s =
ans =
'Boston' 'Detroit' 'Miami'
10 20 30 35

A cell array can be used to store any type


To add another row to the end of the cell
of data, including other cell arrays. One
array:
use of a cell array is to store all of the input
arguments for a function:

>> c(end+1) = {1:2:10}

c = >> xP = {x, P}

[1x4 double] [40] [1x2 double] xP =

[1x5 double] [1x2 double] [3x2 double]

>> c{end} The arguments can then be passed to a


ans = function by generating a comma-
separated list from the cell array:
1 3 5 7 9

>> d = mydist(xP{:})
A common use for cell arrays is to store
d =
text strings:
2

3
>>s={'Miami','Detroit','Boston'}
5
s =

'Miami' 'Detroit' 'Boston'


Cell arrays of can be created using the cell
function:
s =

>> c = cell(1,3) Name: 'Mike'

c =

[] [] [] >> s.Age = 44

s =

Name: 'Mike'
Non-empty values can then be assigned to
each element using a FOR Loop (see Age: 44
Section 11 below).

Structures can be combines into structure


A cell array can be both created and arrays:
assigned non-empty values by using the
deal function:
>> s(2).Name = 'Bill'

s =
>> [c2{1:3}] = deal(0)
1x2 struct array with fields:
c2 =
Name
[0] [0] [0]
Age
>> [c3{1:3}] = deal(1,2,3)

c3 =
>> s(2).Age = 40;
[1] [2] [3]
s(2)

ans =
Structures
Name: 'Bill'
Structures are used to group together
related information. Age: 40

s.Name
Each element of a structure is a field:
ans =

Mike
>> s.Name = 'Mike'
ans = D3 =

Bill 1 2 3

4 5 6

An alternate way to do the same thing that


is sometimes more efficient is to use a >> D3(:,:,2) = [7 8 9; 10 11 12]
single structure instead of an array of
structures and use an array for each field
of the structure:
>> D3(:,:,1) =

1 2 3
>> t.Name = {'Mike','Bill'}
4 5 6
t =

Name: {'Mike' 'Bill'}


>> D3(:,:,2) =

7 8 9
>> t.Age = [44 40]
10 11 12
t =

Name: {'Mike' 'Bill'}


To access individual elements and cross-
Age: [44 40] sections:

N-D Arrays >> D3(1,3,2)

Multidimensional, or N-D, arrays extend ans =


the basic 2-D array used in MATLAB. N-D
9
arrays cannot be stored as sparse arrays,
so they should only be used for dense
arrays. N-D array can be created by
>> D3(:,1,:)
extending a 2-D array or by directly
creating the array using functions like ans(:,:,1) =
zeros and ones:
1

4
>> D3 = [1 2 3; 4 5 6]
i =

>> ans(:,:,2) = 1

7 i =

10 2

To convert the 3-D answer to a 2-D array: i =

>> D2 = squeeze(D(:,1,:))

D2 = >> for i = 5:-2:1, i, end

1 7

4 10 i =

5
1.3.11. Control Structures i =

In MATLAB, FOR loops iterate over the i =


columns of an array, and logical
1
expressions are used for conditional
evaluation in IF statements and WHILE
loops.
Any type of array can be used; e.g., a
character array:
FOR Loop

>> chararray = 'abc'


>> for i = 1:3

chararray =
i abc

>> for i = chararray


end i
end

i = ??? Error using ==> +

a Function '+' is not defined for


values of class 'cell'.
i =

b
>> for i = 1:length(c),
i =
c{i} = c{i} + 1;
c
end

Because any type of array can be used in a


FOR loop, using FOR loops can greatly slow The function length is equal to
down the execution speed of MATLAB as max(size(c)). To see the contents of each
compared to the equivalent array element in cell array:
operation (although FOR loops with only
scalar arithmetic inside have been
optimized in Release 13 of MATLAB so that >> c{:}
there is no performance penalty).
ans =

11 21 31
Most of the standard arithmetic
ans =
operations and functions in Matlab cannot
be directly applied to an entire cell array; 41
instead, a FOR loop can used to apply the
ans =
operation or function to each element of
the cell array: 51 61

>> c = {[10 20 30],[40],[50 60]}


IF Statement
c =

[1x3 double] [40] [1x2 double] >> n = 3;

>> if n > 0
>> c = c + 1 disp('Positive value.')
elseif n < 0

disp('Negative value.') end

else n =

disp('Zero.') 1

end n =

WHILE Loop n =

>> while n > 0

n = n - 1 The DO-WHILE loop is used to ensure that


the statements inside the loop are
end
evaluated at least once even if the logical
n = expression is not true. The logical
expression in a conditional statement must
2 evaluate to a single logical scalar value. To
n = convert a logical vector to a scalar, the
functions any and all can be used:
1

n =
>> a = [5 0 -1 9 0];
0
>> a > 0

DO-WHILE Loop ans =

1 0 0 1 0
>> done = 0;

>> while ~done >> any(a > 0)


n = n + 1

ans =
if n >= 3, done = 1; end 1
>> all(a > 0)

ans = 0
Basic Concepts in MATLAB

1.4 Review Questions


1. Write a code to generate a 4x3 matrix of random integers. Save it with a variable name X, save
its diagonal elements in another variable D, save these variables in a file with your name, clear
the variables from workspace, how these variables can be restored back?

______________________________________________________________________

______________________________________________________________________

A= 1 2 3 4 B= 11 22 33 44
2. Let’s
[
5 6 7 8 ] , and
[
55 66 77 88 ] , Combine these two matrices in
such a way that the resultant should be

RES= 55 66 77 88 4 3 2 1
[
11 22 33 44 8 7 6 5 .
]
______________________________________________________________________

______________________________________________________________________

3. Create your own function named as triarea; find the sum of two triangle areas using that
function. The values of all the sides’ measurements should be entered at run time.
______________________________________________________________________

______________________________________________________________________
4. Which of the numbers in A = [1 4 5 6 8 10 12 15 16 18 20] are divisible by 5, How would you
determine through MATLAB functions. Write sequence of instructions.

______________________________________________________________________

______________________________________________________________________

5. 10 students are to be assigned different grades like A, B & C. Save them and after saving,
arrange them through MATLAB function according to their grades i.e. A grade acquiring students
should be placed first then B grade holders, then C.

______________________________________________________________________

______________________________________________________________________

6. Write a program using else if structure to display even and odd numbers from 1 to 20.

______________________________________________________________________

Institute of information & Communication Technology (IICT), MUET 26


Basic Concepts in MATLAB

______________________________________________________________________
Due acknowledgments to authors of Lab Book on Neural Network & Fuzzy Logic with MATLAB

Institute of information & Communication Technology (IICT), MUET 27

You might also like