writing a linspace() function using nargin checks in matlab

Here is a possible implementation of a linspace function written in MATLAB that uses nargin checks:

main.m
function y = mylinspace(varargin)
%MYLINSPACE Create equally spaced points between two values.
%   Y = MYLINSPACE(X1, X2) generates a row vector Y of 100 equally spaced
%   points between X1 and X2.
%
%   Y = MYLINSPACE(X1, X2, N) generates a row vector Y of N equally spaced
%   points between X1 and X2.
%
%   If X2 is less than X1, then the points are generated in decreasing
%   order.
%
%   The syntax is the same as MATLAB's built-in linspace function.

narginchk(2, 3);
if nargin == 2
    % default number of points
    n = 100;
else
    n = varargin{3};
end
y = linspace(varargin{1}, varargin{2}, n);
end
613 chars
23 lines

This mylinspace function checks the number of input arguments using the narginchk function with the minimum and maximum number of arguments allowed. If only two arguments are given, the function generates 100 equally spaced points by default. If three arguments are given, the third argument is the number of points requested. The function then calls the built-in linspace function with the input arguments and returns the result.

related categories

gistlibby LogSnag