write your own version of the linspace function in matlab

Here's an implementation of the linspace function in MATLAB:

main.m
function [x] = my_linspace(x1, x2, n)
%MY_LINSPACE Generates a row vector of n evenly spaced points between x1 and x2.
%   x = MY_LINSPACE(x1, x2, n) generates a row vector x of n points
%   between x1 and x2.
    step = (x2-x1)/(n-1);
    x = x1:step:x2;
end
260 chars
8 lines

This function takes in the starting value x1, the ending value x2, and the number of points n that should be evenly spaced between those two values. It then calculates the step size between each point ((x2 - x1)/(n-1)) and generates a row vector of n evenly spaced points starting at x1 and incrementing by step until x2 is reached.

You can call this function just like you would the built-in linspace function:

main.m
x = my_linspace(0, 1, 5);
26 chars
2 lines

This would generate a row vector x with 5 evenly spaced points between 0 and 1:

main.m
x = [0 0.25 0.5 0.75 1]
24 chars
2 lines

related categories

gistlibby LogSnag