Matlab function that does (0: N-1) / N * M

I would like to create 20 evenly spaced corners. Here are two not very accurate solutions:

n = 20;

% unnecessary line
angles = linspace(0,2*pi,n+1);
angles = angles(1:end-1)

% intention unclear
angles = (0:n-1)/n * 2*pi

Is there an- linspacelike function that makes this better?

+3
source share
1 answer

linspacewritten to Matlab (i.e. it is not a built-in function). You can easily change its code so as not to generate the last element, and save it as another function.

In fact, if you see the code linspace, you will notice that the last item needs to be added specifically. So your guess was correct: it is more "natural" so as not to include the last element.

In the code below, I include the modified three lines and the original ones for comparison.

function y = linspace2(d1, d2, n)

if nargin == 2
    n = 100;
end
n = double(n+1); %// modified line
%// Originally: n = double(n);
n1 = floor(n)-1;
vec = 0:n-2;
if isinf(d2 - d1) 
    y = d1 + (d2/n1).*vec - (d1/n1).*vec; %// modified line
    %// Originally: y = [d1 + (d2/n1).*vec - (d1/n1).*vec, d2];
else
    y = d1 + (vec.*(d2-d1)/n1); %// modified line
    %// Originally: y = [d1 + (vec.*(d2-d1)/n1), d2];
end
0
source

All Articles