The fastest way I can think of is calculating the step-size, construct the vector from that using implicit binary expansion.
a = [ -1; 0; 1];
n = 3;
stepsizes = (max(a,0)-min(a,0))/(n-1);
A = min(a,0) + (0:(n-1)).*stepsizes;
Timeit:
A couple of timeit results using (use timeit(@SO) and remove comments from the blocks to be timed):
function SO()
n = 1e3;
m = 1e5;
a = randi(9,m,1)-4;
% %Wolfie
% aminmax = [min(a, 0), max(a,0)]';
% A = interp1( [0,1], aminmax, linspace(0,1,n) )';
% %Nicky
% stepsizes = (max(a,0)-min(a,0))/(n-1);
% A = min(a,0) + (0:(n-1)).*stepsizes;
% %Loop
% A = zeros(m,n);
% for i=1:m
% A(i,:) = linspace(min(a(i),0),max(a(i),0),n);
% end
%Arrayfun:
A = cell2mat(arrayfun(@(x) linspace(min(x,0),max(x,0),n),a,'UniformOutput',false));
Then the times are:
- Wolfie: 2.2243 s
- Mine: 0.3643 s
- Standard loop: 1.0953 s
arrayfun: 2.6298 s
Videos
The fastest way I can think of is calculating the step-size, construct the vector from that using implicit binary expansion.
a = [ -1; 0; 1];
n = 3;
stepsizes = (max(a,0)-min(a,0))/(n-1);
A = min(a,0) + (0:(n-1)).*stepsizes;
Timeit:
A couple of timeit results using (use timeit(@SO) and remove comments from the blocks to be timed):
function SO()
n = 1e3;
m = 1e5;
a = randi(9,m,1)-4;
% %Wolfie
% aminmax = [min(a, 0), max(a,0)]';
% A = interp1( [0,1], aminmax, linspace(0,1,n) )';
% %Nicky
% stepsizes = (max(a,0)-min(a,0))/(n-1);
% A = min(a,0) + (0:(n-1)).*stepsizes;
% %Loop
% A = zeros(m,n);
% for i=1:m
% A(i,:) = linspace(min(a(i),0),max(a(i),0),n);
% end
%Arrayfun:
A = cell2mat(arrayfun(@(x) linspace(min(x,0),max(x,0),n),a,'UniformOutput',false));
Then the times are:
- Wolfie: 2.2243 s
- Mine: 0.3643 s
- Standard loop: 1.0953 s
arrayfun: 2.6298 s
Take a = [ -1; 0; 1]. Create the min / max array:
aminmax = [min(a, 0), max(a,0)].';
Now use interp1
N = 3; % Number of interpolation points.
b = interp1( [0,1], aminmax, linspace(0,1,N) ).';
>> b =
-1.0000 -0.5000 0
0 0 0
0 0.5000 1.0000
There are a couple of ways you can do this:
Using the colon operator:
startValue = 1; endValue = 10; nElements = 20; stepSize = (endValue-startValue)/(nElements-1); A = startValue:stepSize:endValue;Using the
linspacefunction (as suggested by Amro):startValue = 1; endValue = 10; nElements = 20; A = linspace(startValue,endValue,nElements);
Keep in mind that the number of elements in the resulting arrays includes the end points. In the above examples, the difference between array element values will be 9/19, or a little less than 0.5 (unlike the sample array in the question).
linspace generates linearly spaced vectors:
>> A = linspace(1, 10, 20-1)
ans =
1 1.5 2 2.5 3 3.5 ... 9.5 10