writing a linspace() function using nargin checks and not varargin in matlab

You can write a linspace function by using nargin checks in MATLAB. Here's an example implementation:

main.m
function out = my_linspace(start_val, end_val, num_points)

if nargin < 3
    num_points = 100;
end

out = linspace(start_val, end_val, num_points);

end
154 chars
10 lines

In this implementation, we first check the number of input arguments using nargin. If there are less than 3 arguments, we set num_points to the default value of 100. We then call MATLAB's built-in linspace function with the input arguments and return the result.

With this implementation, you can call the function like this:

main.m
>> my_linspace(0, 1, 5)

ans =

         0    0.2500    0.5000    0.7500    1.0000
83 chars
6 lines

This will return a row vector of 5 equally spaced values between 0 and 1.

Note that we did not use varargin in this implementation because varargin is used to capture an arbitrary number of input arguments. In this case, we only need to capture up to three input arguments, so using nargin checks is a simpler and more efficient approach.

related categories

gistlibby LogSnag