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 scalar (single-element) quantities.
a = 2; b = 3; c = a + b
c =
5
MATLAB variables can also represent arrays or matrices
a = [1 2 3 4]; b = [4 5 6 7]; c = a + b
c =
5 7 9 11
Even though you may not make the distinction, MATLAB always treats arrays as vectors. MATLAB has two ways of representing vectors: row vectors and column vectors
this is a row vector
a = [1 2 3 4]
a =
1 2 3 4
and this is a column vector
b = [4; 5; 6; 7]
b =
4
5
6
7
You cannot add a row vector to a column vector. Trying to do so results in a error message. (we'll discuss the "try" and "catch" commands later... they are used here to allow execution to continue after the error)
try c = a + b catch lasterr end
ans = Error using ==> plus Matrix dimensions must agree.
there are several ways to check on the size of an array to find out if it is a row- or column-vector, including the size command and the whos command.
The size command returns the size of a scalar, vector or matrix. The answer is a row vector with the number of rows and columns.
size(a)
ans =
1 4
size(b)
ans =
4 1
as you can see, a is a row vector (1 row, 4 columns) and b is a column vector (4 rows, 1 column).
The whos command lists all the variables in the current workspace, together with information about their size, bytes, class, etc.
whos
Name Size Bytes Class a 1x4 32 double array ans 1x2 16 double array b 4x1 32 double array ball 1x1 560 struct array c 1x4 32 double array Grand total is 26 elements using 672 bytes
whos var1 var2... restricts the display to the variables specified.
whos a b
Name Size Bytes Class a 1x4 32 double array b 4x1 32 double array Grand total is 8 elements using 64 bytes
as we can see from above, a and b have different sizes therefore we cannot add them together directly.
Sometimes in MATLAB, you'll end up with one variable that's a row vector and one that's a column vector. Here are some ways to add them together, provided they have the same length (number of elements.
transpose a
c = a' + b
c =
5
7
9
11
transpose b
c = a + b'
c =
5 7 9 11
force a and b to both be column vectors (this works under the broadest range of conditions)
c = a(:) + b(:)
c =
5
7
9
11
the third element of a
a(3)
ans =
3
first three elements of b
b(1:3)
ans =
4
5
6
the last element of a
a(end)
ans =
4