Compatible Array Sizes for Basic Operations - MATLAB & Simulink (original) (raw)

Main Content

Most binary (two-input) operators and functions in MATLABĀ® support numeric arrays that have compatible sizes. Two inputs have compatible sizes if, for every dimension, the dimension sizes of the inputs are either the same or one of them is 1. In the simplest cases, two array sizes are compatible if they are exactly the same or if one is a scalar. MATLAB implicitly expands arrays with compatible sizes to be the same size during the execution of the element-wise operation or function.

Inputs with Compatible Sizes

2-D Inputs

These are some combinations of scalars, vectors, and matrices that have compatible sizes:

Multidimensional Arrays

Every array in MATLAB has trailing dimensions of size 1. For multidimensional arrays, this means that a 3-by-4 matrix is the same as a matrix of size 3-by-4-by-1-by-1-by-1. Examples of multidimensional arrays with compatible sizes are:

Empty Arrays

The rules are the same for empty arrays or arrays that have a dimension size of zero. The size of the dimension that is not equal to 1 determines the size of the output. This means that dimensions with a size of zero must be paired with a dimension of size 1 or 0 in the other array, and that the output has a dimension size of 0.

 A: 1-by-0     
 B: 3-by-1

Result: 3-by-0

Inputs with Incompatible Sizes

Incompatible inputs have sizes that cannot be implicitly expanded to be the same size. For example:

Examples

Subtract Vector from Matrix

To simplify vector-matrix operations, use implicit expansion with dimensional functions such as sum, mean,min, and others.

For example, calculate the mean value of each column in a matrix, then subtract the mean value from each element.

ans =

 3    -4     1
-2     0     2
-1     4    -3

Add Row and Column Vector

Row and column vectors have compatible sizes, and when you perform an operation on them the result is a matrix.

For example, add a row and column vector. The result is the same asbsxfun(@plus,a,b).

ans =

 6     7     8     9
 7     8     9    10
 8     9    10    11

See Also

bsxfun