Professional Documents
Culture Documents
Basic Concepts in Matlab: Michael G. Kay
Basic Concepts in Matlab: Michael G. Kay
Michael G. Kay
Fitts Dept. of Industrial and Systems Engineering
North Carolina State University
Raleigh, NC 27695-7906, USA
kay@ncsu.edu
September 2010
Contents
1. The Matlab Environment
2. Creating Arrays
3. Saving and Loading Variables
4. Selecting Array Elements
5. Changing and Deleting Array Elements
6. Manipulating Arrays
7. Multiplication and Addition
8. Functions and Scripts
9. Anonymous Functions
10. Example: Minimum-Distance Location
11. Logical Expressions
12. Cell Arrays, Structures, and N-D Arrays
13. Control Structures
14. Example: Random Walk Simulation
15. Logical vs. Index Arrays
16. Example: The Monti Carlo Method
17. Full vs. Sparse Matrices
18. Inserting and Extracting Array Elements
19. List of Functions Used
1
1
2
3
3
4
4
6
8
8
9
9
11
13
13
14
16
16
16
2. Creating Arrays
The basic data structure in Matlab is the two-dimensional
array. Array variables can be scalars, vectors, or matrices:
n = 1
n =
1
a = [1 2 3]
a =
A = [1 2 3 4; 5 6 7 8]
a = rand(1,3)
A =
1
a =
0.6086
0.2497
0.8154
0.4760
0.3661
b = rand(1,3)
b =
0.2618
A = [1 2 3 4; 5 6 7 8];
randperm(5)
ans =
a = []
a =
eye(3)
ans =
a = 1:5
a =
1
a = 1:2:5
a =
1
a = 10:-2:1
a =
10
whos
Name
a = ones(1,5)
a =
1
a = ones(5,1)
a =
1
Size
Bytes
Class
2x4
64
double array
1x3
24
double array
ans
3x3
72
double array
1x3
24
double array
1x1
double array
save myvar A a
a = zeros(1,5)
a =
0
clear
whos
A(:,end-1)
load myvar
ans =
Data files can also be saved and loaded using the File menu.
3
7
B = A(:,3:end)
B =
A
A =
1
A(:,:)
diag(B)
ans =
ans =
3
8
A(1,2)
ans =
2
A(1,:)
ans =
1
A(:,1)
ans =
1
a = 1:5
5
a =
A(:,[1 3])
ans =
a(2) = 6
1
a =
1
a([1 3]) = 0
a =
6
a([1 3]) = [7 8]
A(:,end)
a =
ans =
MANIPULATING ARRAYS
A(1,2) = 100
[A B]
A =
ans =
(Concatenate matrices)
100
a(3) = []
ans =
a =
7
10
20
30
40
50
60
a([1 4]) = []
a =
A(:)
6
ans =
1
5
A(:,2) = []
A =
7
1
4
8
(Convert matrix to row vector)
6. Manipulating Arrays
A = A(:)'
A =
A = reshape(A,2,3)
A =
A =
1
(Transpose)
A'
ans =
1
Scalars
(Flip left/right)
fliplr(A)
A =
ans =
4
2 + A
(Flip up/down)
flipud(A)
ans =
ans =
5
10
B = 2 * A
43
Division (./) and power (.^) operators can also be
preformed element by element.
B =
2
10
14
16
Addition
Matrices are added together in Matlab element by element;
thus, each matrix must be the same size; i.e.,
Multiplication
Matrices are multiplied together in two different ways:
element-by-element multiplication, indicated by the use of a
dot (.) along with the operator, and matrix multiplication,
where the inner dimensions of the matrices must be the
same; i.e.,
Addition:
C = A + B
C =
Element-by-element multiplication:
Matrix multiplication:
A mn Bmn C mn
12
A mn Bn p Cm p
15
21
24
(23 .* 23 = 23)
C = A .* B
C =
2
18
32
50
98
128
(Matrix multiplication)
ones(2,1) * a
ans =
(Error: 23 * 23 23)
A * B
A mn Bmn C mn
C = A * B'
C =
52
116
116
276
C =
52
76
88
76
116
136
88
136
160
11
(Tonys Trick)
3
(Replicate array)
ans =
a =
3
(13 * 31 = 11)
Summation
ans =
14
A * a'
repmat(a,2,1)
a = 1:3
a * a'
ans =
(32 * 23 = 33)
a(ones(2,1),:)
C = A' * B
(23 * 31 = 21)
a = 1:5
ans =
a =
19
ans =
5
(Array summation)
sum(a)
ans =
15
(Cumulative summation)
cumsum(a)
ans =
1
10
15
10
12
sum(A)
ans =
6
sum(A,2)
ans =
8
20
x x1
sum(A,1)
ans =
6
10
12
(Sum entire matrix)
sum(sum(A))
ans =
A =
1
sum(A)
4
(Incorrect)
ans =
8
sum(A, 1)
p1,2
pm ,2
2
2
x 1 pm ,1 x 2 pm ,2
x 1 p1,1 x 2 p1,2
2
28
A = A(1,:)
p1,1
x2 , P
pm ,1
(Correct)
9
25
5
d =
2
3
1
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
x = [3 1];
edit mydist
P = [1 1; 6 1; 6 5]
P =
1
d = sqrt(sum((ones(3,1)*x - P).^2,2));
ones(3,1) * x
Save the file, then check to see if Matlab can find the file by
using the type command to print the function at the
command line, and then check to see that it works as
desired:
ans =
type mydist
function d = mydist(x,P)
function d = mydist(x,P)
d = sqrt(sum((ones(3,1)*x - P).^2,2));
d = mydist(x,P)
ones(3,1)*x - P
d =
ans =
-3
-3
-4
(ones(3,1)*x - P) .^ 2
ans =
2.8284
16
4.2426
d =
7.0711
sum((ones(3,1)*x - P).^2, 2)
ans =
4
ANONYMOUS FUNCTIONS
m = size(P,1)
9. Anonymous Functions
m =
x = [3 1];
n = size(P,2)
P = [1 1; 6 1; 6 5];
n =
ans =
9
sumMydist([4 3])
To get help:
ans =
help mydist
9.2624
d = mydist(x,P)
x0 = [0 0];
[x,sumd] = fminsearch(sumMydist,x0)
sumd = sum(mydist(x,P))
x =
5.0895
sumd =
1.9664
sumd =
10
8.6972
LOGICAL EXPRESSIONS
a(a ~= 0) = a(a ~= 0) + 1
x =
5.0895
a =
1.9663
sumd =
-1
8.6972
Cell Arrays
A cell array is a generalization of the basic array in Matlab
that can have as its elements any type of Matlab data
structure. Curly braces, { }, are used to distinguish a cell
array from a basic array.
a = [4 0 -2 7 0]
a =
4
-2
c =
(Greater than)
a > 0
[1x3 double]
ans =
1
(Equal to)
c{1}
ans =
0
ans =
0
10
a ~= 0
ans =
(Logical AND)
10
ans =
(a < 0) | (a > 4)
c{1}(end+1) = 35
(Logical OR)
c =
ans =
0
[1x4 double]
0
10
0
30
35
c(end+1) = {1:2:10}
c =
a(a > 0)
[1x4 double]
[1x5 double]
ans =
7
[1x2 double]
ans =
a =
1
0
[40]
c{end}
a(a == 7) = 8
20
[1x2 double]
ans =
ans =
1
[40]
c{1}
(Logical NOT)
30
c{1}(1)
0
20
ans =
1
[1x2 double]
a == 7
[40]
-2
s =
s = {'Miami','Detroit','Boston'}
Name: 'Mike'
s.Age = 44
s =
'Miami'
'Detroit'
'Boston'
s =
Name: 'Mike'
s = sort(s)
Age: 44
Structures can be combines into structure arrays:
s =
'Boston'
'Detroit'
s(2).Name = 'Bill'
'Miami'
s =
1x2 struct array with fields:
xP = {x, P}
Name
xP =
Age
[1x2 double]
s(2).Age = 40;
[3x2 double]
s(2)
ans =
d = mydist(xP{:})
Name: 'Bill'
d =
Age: 40
2
s.Name
ans =
Mike
ans =
c = cell(1,3)
Bill
c =
[]
[]
[]
s =
struct('Name',{'Mike','Bill'},'Age',{44,40})
s =
1x2 struct array with fields:
[c2{1:3}] = deal(0)
Name
c2 =
Age
[0]
[0]
[0]
[c3{1:3}] = deal(1,2,3)
names = {s.Name}
c3 =
[1]
[2]
names =
[3]
'Mike'
'Bill'
Structures
ages = [s.Age]
ages =
44
s.Name = 'Mike'
10
40
CONTROL STRUCTURES
D2 = squeeze(D3(:,1,:))
D2 =
t.Name = {'Mike','Bill'}
t =
Name: {'Mike'
'Bill'}
10
t =
Name: {'Mike'
'Bill'}
FOR Loop
for i = 1:3
N-D Arrays
end
i =
1
D3 = [1 2 3; 4 5 6]
i =
D3 =
2
1
i =
3
D3(:,:,2) = [7 8 9; 10 11 12]
D3(:,:,1) =
i =
5
i =
D3(:,:,2) =
10
11
12
i =
1
D3(1,3,2)
chararray = 'abc'
ans =
9
chararray =
D3(:,1,:)
abc
ans(:,:,1) =
for i = chararray
end
ans(:,:,2) =
i =
10
i =
11
CONTROL STRUCTURES
i =
WHILE Loop
while n > 0
n = n - 1
end
n =
2
n =
1
n =
0
DO-WHILE Loop
[1x3 double]
[40]
[1x2 double]
done = 0;
c = c + 1
while ~done
n = n + 1
n =
1
n =
c{:}
ans =
11
n =
21
31
ans =
41
ans =
51
61
IF Statement
a = [5 0 -1 9 0];
n = 3;
a > 0
if n > 0
ans =
disp('Positive value.')
elseif n < 0
any(a > 0)
disp('Negative value.')
ans =
else
disp('Zero.')
all(a > 0)
end
ans =
Positive value.
12
-2
rand('state',123)
s = rand(1,5)
-4
s =
0.0697
0.2332
0.7585
0.6368
-6
0
0.7374
20
ans =
0
ans =
0
60
70
80
90
100
2t
for i = 1:100
d = cumsum(((rand(1,1000)>0.5)*2)-1);
ans =
-1
dt(i) = d(end);
end
d =
mean(abs(dt))
-1
50
-1
40
E d ( t )
(s > 0.5)*2
30
s > 0.5
10
-2
-1
(Sample mean)
ans =
24.2200
s = rand(1,100);
2(1, 000)
25.2313
plot(d)
ispos = a > 0
ispos =
13
-1
0
(Logical array)
a =
a(ispos)
(Index array)
-1
a(idxpos)
ans =
9
idx = [1 2 1];
a(idx)
s = {'Miami','Detroit','Boston'};
ans =
idxDetroit = strmatch('Detroit',s)
idxDetroit =
isDetroit = strcmpi('detroit',s)
isDetroit =
1
idxa =
idxpos =
sa =
-1
ans =
5
mina =
idxmina =
-1
P ( x 2 y 2 1)
Acircle r 2 m
Asquare
4
4 n
14
4m
.
n
piestimate = 4 * m/n
piestimate =
2.6667
pi
ans =
3.1416
-1
n = 5000;
XY = rand(n,2) * 2 - 1;
-1
m = sum(isin)
m =
3967
piestimate = 4 * m/n
piestimate =
rand('state',123)
3.1736
n = 3;
pi
XY = rand(n,2)
ans =
XY =
0.0697
0.7585
0.2332
0.6368
0.7374
0.6129
3.1416
To plot results:
plot(XY(isin,1),XY(isin,2),'b.')
axis equal
XY = XY * 2 - 1
XY =
-0.8607
0.5171
-0.5335
0.2737
0.4749
0.2257
15
B(A ~= 0) = A(A ~= 0)
B =
1
30
10
20
A = [0 0 0 30; 10 0 20 0]
A =
0
30
10
20
sparse(A)
ans =
ans =
30
(2,1)
10
10
20
(2,3)
20
10
20
(1,4)
30
full(A)
b =
ans =
30
30
10
10
20
20
deal
length
sort
diag
load
sparse
disp
mean
sqrt
doc
min
squeeze
eye
ones
strcmpi
find
rand
strmatch
fliplr
randperm
struct
flipud
repmat
sum
A =
(2,1)
10
(2,3)
20
(1,4)
30
16
fminsearch reshape
type
full
save
whos
help
size
zeros