Validating Function Inputs in a modern way

Messages in english

Modérateur : xcasadmin

compsystems
Messages : 554
Inscription : sam. févr. 04, 2017 11:34 pm
Localisation : Colombia
Contact :

Validating Function Inputs in a modern way

Message par compsystems » jeu. janv. 09, 2020 10:58 pm

An interesting video and information on how to validate arguments in a modern way (MatrixLab)

Create rectangle coordinates
before

Code : Tout sélectionner

function rectCoords = createRectangleCoords(width, height, varargin)
%CREATERECTANGLECOORDS Easily create coordinates for rectangle given its width 
%and height
	% Error check required input arguments 
	if nargin < 1
		error("rectangle requires width and height values"); 
	elseif ~isnumeric(width) || ~isscalar(width)
		error("width must be a scalar numeric value") 
	elseif ~isnumeric(height) || ~isscalar(height)
		error("height must be a scalar numeric value") 
	end
	
	% Process optional inputs xStart and yStart 
	xStart = 0;
	if nargin > 2 && isnumeric(varargin{1}) && isscalar(varargin{1}) 
		xStart = varargin{l};
	end
	yStart = 0;
	if nargin > 3 && isnumeric(varargin{2}) && isscalar(varargin{2}) 
		yStart = varargin{2}; 
	end
	% Create rectangle coordinates 
	rectCoords = ...
	[xStart	yStart
	xStart+width yStart 
	xStart+width yStart+height 
	xStart	yStart+height];
end
Now

Code : Tout sélectionner

function rectCoords = createRectangleCoords(width, height, xStart, yStart)
%CREATERECTANGLECOORDS Easily create coordinates for rectangle given its Xwidth and height
	arguments
		width	(1,1)	double	{mustBeNumeric}
		height	(1,1)	double	{mustBeNumeric}
		xStart	(1,1)	double	{mustBeNumeric} =0;	% optional
		yStart	(1,1)	double	{mustBeNumeric} =0;	% optional
	end
...

Code : Tout sélectionner

function quadHandle = plotQuadrilateral(xCoords, yCoords, options)

arguments
	xCoords (1,4) double {mustBeNumeric} 
	yCoords (1,4) double {mustBeNumeric}

	% Name/Value pairs

	options.LineType (1,1) string = "-"
	options.LineThickness (1,1) double {mustBePositive} = 1;
end
..
Source:
https://www.mathworks.com/videos/valida ... 23207.html

Répondre