writing your own linspace() function using nargin check, isnumeric, isscalar in matlab

Here's an implementation of the linspace() function that checks for the number of input arguments (nargin), whether they are numeric (isnumeric()) and whether scalar values are passed (isscalar()):

main.m
function output_array = my_linspace(start_value, end_value, number_of_values)

% Check the number of input arguments
if nargin < 2
    error('At least two input arguments are required');
end

% Set default number of values
if nargin < 3
    number_of_values = 100;
end

% Check for numeric input arguments
if ~isnumeric(start_value) || ~isnumeric(end_value) || ~isnumeric(number_of_values)
    error('All input arguments must be numeric');
end

% Check for scalar input arguments
if ~isscalar(start_value) || ~isscalar(end_value) || ~isscalar(number_of_values)
    error('All input arguments must be scalar');
end

% Calculate delta between start and end values
delta = (end_value - start_value) / (number_of_values - 1);

% Calculate output array
output_array = start_value:delta:end_value;

end
797 chars
30 lines

This implementation uses the error() function to throw errors when an invalid input argument is passed. It also sets a default value of 100 for the number of values if it is not provided as an input argument.

related categories

gistlibby LogSnag