Page 1 sur 1

### Validating Function Inputs in a modern way

Publié : 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