MATLAB techniques for modeling and simulation
MCB 419: Brain, Behavior and Information Processing
M. Nelson, Univ. of Illinios, Urbana-Champaign, Jan 2005
MATLAB variables can represent multi-dimensional arrays and matrices. Here's a 2 x 3 array:
a = [1 2 3; 4 5 6]
a =
1 2 3
4 5 6
size(a)
ans =
2 3
and here's a 3 x 2 array:
a = [1 2; 3 4; 5 6]
a =
1 2
3 4
5 6
Here's a 3 x 5 array:
b = [ 1 2 3 4 5;... 0 1 0 1 0;... 9 8 7 6 5]
b =
1 2 3 4 5
0 1 0 1 0
9 8 7 6 5
Note how the use of the line continuation notation (...) improves the readability
individual elements are accessed using subscripts (indices)
To refer to a particular element:
c = b(3, 3)
c =
7
To refer to a particular row:
c = b(1, :)
c =
1 2 3 4 5
here the colon (:) notation can be thought of as a "wildcard" representing "all", so (1,:) translates to "first row, all columns"
To refer to a particular column:
c = b(:, 5)
c =
5
0
5
where (:,5) translates to "all rows, fifth column".
To refer to a range of rows and/or columns:
c = b(1:2, 3:5)
c =
3 4 5
0 1 0
where (1:2, 3:5) translates to "rows 1-2, columns 3-5".
As a reminder, here's what b looks like:
b
b =
1 2 3 4 5
0 1 0 1 0
9 8 7 6 5
it's often useful to initialize a matrix to all zeros or all ones using the built-in zeros and ones functions:
a = zeros(3,2)
a =
0 0
0 0
0 0
b = ones(2,3)
b =
1 1 1
1 1 1
here's a 3 x 3 matrix, with all values initialized to "pi":
c = pi*ones(3,3)
c =
3.1416 3.1416 3.1416
3.1416 3.1416 3.1416
3.1416 3.1416 3.1416
the same technique can be used to initialize vectors
d = zeros(1,6)
d =
0 0 0 0 0 0
Note that zeros(6) creates a 6 x 6 array of zeros, not a 6 x 1 or 1 x 6 array, as might be expected:
d = zeros(6)
d =
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0