Main Content

mustBeReal

Validate that value is real

Description

example

mustBeReal(value) throws an error if value is not a real number. This function does not return a value.

mustBeReal calls the following function to determine if the input is real:

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

This function ignores input arguments that are empty values. Therefore, no error is thrown when the property or function argument value is empty.

Examples

collapse all

Use mustBeReal to validate that the input is a real number.

Validate that a calculation results in real numbers.

x = -2:2;
z = x.^exp(-x.^2);
mustBeReal(z)
values must be real.

The value z is complex.

This class restricts the value of Prop1 to real values.

classdef MyClass
   properties
      Prop1 {mustBeReal}
   end
end

Create an object and assign a value to its property.

x = -2:0.1:2;
obj = MyClass;
obj.Prop1 = x.^exp(-x.^2);
Error setting 'Prop1' property of 'MyClass' class:
values must be real.

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

This function restricts the input argument to a scalar, real value.

function r = mbReal(z)
    arguments
        z (1,1) {mustBeReal}
    end
    r = randi(9,z);
end

Calling this function with a complex value results in an error being thrown by mustBeReal.

x = -1;
z = x.^exp(-x.^2);
r = mbReal(z);
Error using mbReal
 r = mbReal(z);
            ↑
Invalid input argument at position 1. Value must be real.

Input Arguments

collapse all

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

Other data types cause an error.

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

Tips

  • mustBeReal 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 R2017a