writing your own linspace() function without using linspace in matlab

Here's an example implementation of a linspace_custom function in MATLAB:

main.m
function y = linspace_custom(start, stop, num)
%LINSPACE_CUSTOM Returns a row vector with "num" linearly spaced elements from "start" to "stop".

% Check inputs
if nargin < 2
    error("Not enough input arguments. Expected at least 2.");
end

if nargin < 3
   num = 100;
end

% Make sure input types match
if ~isa(start, 'double') || ~isa(stop, 'double') || ~isa(num, 'double')
    error('All inputs must be numeric.');
end

% Make sure inputs are finite
if ~all(isfinite([start, stop, num]))
    error('All inputs must be finite.');
end

% Return vector
y = linspace(start, stop, num);

end
592 chars
27 lines

This implementation uses the linspace function internally to generate the desired output vector.

To use this function, simply save it in a file in your MATLAB working directory and call it like any other function. For example:

main.m
x = linspace_custom(0, 1, 10);
31 chars
2 lines

This will return a row vector x with 10 linearly spaced elements between 0 and 1 (inclusive). Note that if you do not specify the num argument, it defaults to 100.

related categories

gistlibby LogSnag