Contenuto principale

mustBeScalar

R2026b

Validate that value is scalar

Since R2026b

    Description

    mustBeScalar(value) throws an error if value is not a scalar. A scalar has dimensions of 1-by-1. This function does not return a value. mustBeScalar calls the isscalar function to determine if the input is a scalar.

    Class support: All numeric classes, logical, char, string, and MATLAB® classes that implement isscalar.

    example

    Examples

    collapse all

    Use mustBeScalar to validate that a value is a scalar.

    Create a 0-by-1 empty array and test whether it is a scalar. Because the first dimension of the array is zero, mustBeScalar throws an error.

    A = zeros(0,1);
    mustBeScalar(A)
    Value must be a scalar.

    Use an arguments block to restrict a function input to a numeric scalar using mustBeScalar and mustBeNumeric.

    The buildVector function creates a row vector with a spacing determined by the function input.

    function v = buildVector(spacing)
        arguments
            spacing {mustBeScalar,mustBeNumeric}
        end
        v = 1:spacing:20;
    end

    Passing a matrix to the buildVector function results in an error.

    spacing = ones(2,2);
    buildVector(spacing)
    Error using buildVector (line 3)
     buildVector(spacing)
                 ^^^^^^^
    Invalid argument at position 1. Value must be a scalar.

    Input Arguments

    collapse all

    Value to validate, specified as a scalar. If you specify a value that is not a scalar, such as a vector or an empty array, the function throws an error.

    Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char | string | struct | table | cell | categorical | datetime | duration | calendarDuration
    Complex Number Support: Yes

    Tips

    • mustBeScalar is designed to be used for property and function argument validation.

    Extended Capabilities

    expand all

    C/C++ Code Generation
    Generate C and C++ code using MATLAB® Coder™.

    GPU Code Generation
    Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.

    Version History

    Introduced in R2026b