Open In App

Function Argument Validation

Last Updated : 30 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

MATLAB is a programming language that is used for solving math problems so it is also a concept of MATLAB programming language. It is basically defined as a process to declare specific restrictions on the function arguments. By using argument validation we can constrain the class, size, and other things. we can also relate these things without writing the code in the body of the function for performing all the test cases given in any problem. Basically it is a declarative approach which enables or used MATLAB desktop tools to extract the whole information about any function by inspection of specific code blocks. By declaring the requirements for arguments we can eliminate all the cumbersome arguments from the function body. we can perform code checking and improve the readability, robustness, and maintainability of our written code.

We can understand with the help of its syntax. the syntax enables us to define the default values in a consistent way. It also defines the process of defining optional, repeating, and name-value arguments.

Syntax: 

function Function(inputArg)
 arguments
  inputArg (dim1,dim2….) ClassName {fcn1, fcn2…} = defaultValue
  end
  %function code
  end

Now here (dim1,dim2….) ClassName {fcn1, fcn2…} is the syntax for input argument validation. Here 

(dim1,dim2...) = size;
ClassName = Class;
{fcn1,fcn2...} = function names; 
  1. Size: It defines the length of each dimension which will be enclosed in parentheses.
  2. Class: It defines the name of a single MATLAB class. the name of the class always starts with an Uppercase letter.
  3. Functions: It defines the names of various functions separated by commas and enclosed in curly braces.

Now we will see that it also defines argument validation in optional code blocks that are identified with the help of keywords argument. If we are using an argument block then we must use an argument block must start before the first executable lines of the function.

The main point is that we can use multiple blocks in a function but the condition is that all blocks must occur before any code that will not be the part of argument block in the code.

Now let’s see one example of function validation to understand the concept better;

Example 1:

Matlab




% MATLAB code for basic argument validation
function out = Function(X,Y,Z)   
    arguments
        X (1,1) string 
        Y (1,:) double
        Z (4,4) cell
    end
  
    % Function code
    ...
end


Output:

 

So here in this function, the output will define specifies the size and class of the three inputs.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads