Main Content

mustBeMatrix

Validate that value is matrix

Since R2024b

Description

mustBeMatrix(value) throws an error if value is not a matrix. A matrix is a two-dimensional array that has a size of m-by-n, where m and n are nonnegative integers. This function does not return a value.

mustBeMatrix calls the following function to determine if the input is a matrix:

Class support: All numeric classes, logical, and MATLAB® classes that overload ismatrix.

example

Examples

collapse all

Use mustBeMatrix to validate that a value is a 2-D matrix.

Create a 3-D array and test whether it is a matrix. Because the array has more than two dimensions, mustBeMatrix throws an error.

a = ones(2,3,2);
mustBeMatrix(a)
Value must be a matrix.

Use an arguments block to restrict the function input to a numeric matrix using mustBeMatrix and mustBeNumeric.

The WeeklyTotals function sums the columns of the input matrix. If the input is empty ([]), the sum is returned as zero.

function r = WeeklyTotals(DailyTotals)
    arguments
        DailyTotals {mustBeMatrix, mustBeNumeric}
    end
    if isempty(DailyTotals)
        r = 0;
    else
        r = sum(DailyTotals,1);
    end
end

An alternative way to validate the inputs is with the arguments block

arguments
    DailyTotals (:,:) {mustBeNumeric}
end

However, the use of (:,:) leads to automatic size conversion of the input into a 2-D matrix. mustBeMatrix is stricter because it throws an error when the input has more than two dimensions.

Call the WeeklyTotals function with a magic square matrix.

W = magic(4);
r = WeeklyTotals(W)
r =

    34    34    34    34

Input Arguments

collapse all

Value to validate, specified as a scalar, vector, or matrix.

Extended Capabilities

Version History

Introduced in R2024b