Main Content

mustBeSparse

Validate that value is sparse

Since R2023b

Description

example

mustBeSparse(value) throws an error if value is not sparse. If value is empty, the function does not throw an error. This function does not return a value.

mustBeSparse calls the issparse function to determine if the input is sparse.

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

Examples

collapse all

Validate that a matrix is sparse. The mustBeSparse function throws an error because the matrix is not sparse.

X = rand(100);
mustBeSparse(X)
Value must be sparse.

This class restricts the value of Prop1 to sparse matrices.

classdef MyClass
   properties
      Prop1 {mustBeSparse}
   end
end

Create an object and assign a value to its property.

x = rand(100);
obj = MyClass;
obj.Prop1 = x.^2;
Error using implicit default value of property 'Prop1' of class 'MyClass'. Value must be sparse.

When you assign a value to the property, MATLAB calls mustBeSparse with the value being assigned to the property. mustBeSparse issues an error because the value assigned to Prop1 is not sparse.

This function restricts the input argument to a 10-by-10 sparse matrix.

function r = sparseDiag(z)
    arguments
        z (10,10) {mustBeSparse}
    end
    r = diag(z);
end

Calling this function with a nonsparse value results in an error thrown by mustBeSparse.

z = eye(10);
r = sparseDiag(z);
Error using sparseDiag
 r = sparseDiag(z);
                ↑
Invalid argument at position 1. Value must be sparse.

Input Arguments

collapse all

Value to validate, specified as a scalar or array of any one of these types:

Other data types cause an error.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical
Complex Number Support: Yes

Tips

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

Extended Capabilities

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

Version History

Introduced in R2023b