Programming and Data Types | ![]() ![]() |
Empty Matrices
A matrix having at least one dimension equal to zero is called an empty matrix. The simplest empty matrix is 0-by-0 in size. Examples of more complex matrices are those of dimension 0
-by-5
or 10
-by-0
-by-20.
To create a 0-by-0 matrix, use the square bracket operators with no value specified.
A = []; whos A Name Size Bytes Class A 0x0 0 double array
You can create empty arrays of other sizes using the zeros
, ones
, rand
, or eye
functions. To create a 0-by-5 matrix, for example, use
E = zeros(0,5)
Operating on an Empty Matrix
The basic model for empty matrices is that any operation that is defined for m
-by-n
matrices, and that produces a result whose dimension is some function of m
and n
, should still be allowed when m
or n
is zero. The size of the result should be that same function, evaluated at zero.
For example, horizontal concatenation
C = [A B]
requires that A
and B
have the same number of rows. So if A
is m
-by-n
and B
is m
-by-p
, then C
is m-by-(n+
p). This is still true if m
or n
or p
is zero.
Many operations in MATLAB produce row vectors or column vectors. It is possible for the result to be the empty row vector
r = zeros(1,0)
C = zeros(0,1)
As with all matrices in MATLAB, you must follow the rules concerning compatible dimensions. In the following example, an attempt to add a 1-by-3 matrix to a 0-by-3 empty matrix results in an error.
[1 2 3] + ones(0,3) ??? Error using ==> + Matrix dimensions must agree.
Some MATLAB functions, like sum
and max
, are reductions. For matrix arguments, these functions produce vector results; for vector arguments they produce scalar results. Empty inputs produce the following results with these functions:
sum
([ ]) is 0
prod
([ ]) is 1
max
([ ]) is [ ]min
([ ]) is [ ]Using Empty Matrices with If or While
When the expression part of an if
or while
statement reduces to an empty matrix, MATLAB evaluates the expression as being false
. The following example executes statement S0
, because A
is an empty array.
A = ones(25,0,4); if A S1 else S0 end
![]() | Command/Function Duality | Errors and Warnings | ![]() |