mustBeNonNan

Validate that value is nonNaN

Description

example

mustBeNonNan(value) issues an error if value is NaN. This function does not return a value.

mustBeNonNan accepts user-defined objects if the class of the object implements this method:

Examples

collapse all

Use mustBeNonNan to validate that no array elements are NaN.

A = 0./[-2 -1 0 1 2];
mustBeNonNan(A)
Error using mustBeNonNan (line 13)
Value must not be NaN.

Division of 0 by 0 is equal to NaN so the array value contains one element that is NaN, which causes an error.

This class restricts the value of Prop1 to nonNaN values.

classdef MyClass
   properties
      Prop1 {mustBeNonNan}
   end
end

Create an object and assign a value to Prop1.

obj = MyClass;
obj.Prop1 = 0./[-2 -1 0 1 2];
Error setting property 'Prop1' of class 'MyClass':
Value must not be NaN.

When you assign a value to the property, MATLAB® calls mustBeNonNan with the value being assigned to the property. mustBeNonNan issues an error because division of 0 by 0 is NaN.

This function declares an input argument that must be a vector of doubles containing no NaN elements.

function s = mbNonNan(x)
    arguments
        x (1,:) double {mustBeNonNan}
    end
    n = length(x);
    m = sum(x)/n;
    s = sqrt(sum((x-m).^2/n));
end

Calling the function with an input that does not meet the requirement of mustBeNonNan results in an error.

values = [12.7, 45.4, 98.9, NaN, 53.1];
s = mbNonNan(values);
Error using mbNonNan
Invalid input argument at position 1. Value must not be NaN.

Input Arguments

collapse all

Value to validate, specified as a scalar or an array of one of the following:

  • All MATLAB numeric classes and logical.

  • MATLAB user-defined classes that implement isnan

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

Extended Capabilities

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

Introduced in R2017a