how to write your own version of linspace() function using narginchks in matlab

Here is an example code of a custom my_linspace function that mimics the behavior of the built-in linspace function in MATLAB. It includes narginchk to ensure that the function is called with two or three input arguments.

main.m
function y = my_linspace(start, stop, count)
    narginchk(2, 3);
    if nargin < 3
        count = 100;
    end
    
    y = linspace(start, stop, count);
end
160 chars
9 lines

This function takes two or three input arguments:

  • start is the scalar starting value for the range.
  • stop is the scalar ending value for the range.
  • count (optional) is the number of equally spaced values between start and stop.

If count is not provided, my_linspace defaults to 100 equally spaced values between start and stop.

The function then calls the built-in linspace function with the input arguments, and returns the vector result.

related categories

gistlibby LogSnag