MATLAB: How to create array of linearly spaced values from starting and ending points

indexinglinspacematrix arraymatrix manipulation

Hello,
I want to create an array (not vector) of linearly space points from a vector of starting and ending points. For example, I want to do the equivalent of,
go = [1;2;3]; %starting point
st = [2;3;4]; %ending points
nGo = length(go); %number of starting points
nPoints = 10; %number of points in each row
for iGo = 1:nGo
A(iGo,:) = linspace(go,st,nPoints); %create array of linearly spaced rows
end
The problem is that the number of start points in on the order of 10000 and it is part of a fitting routine. So, I need the creation of this matrix to be as efficient as possible using minimal loops. Any suggestions?

Best Answer

This method is faster than looping over linspace:
x = linspace(0,1,nPoints);
A2 = go + x.*(st - go);
Here's a timing test for nGo = 10000:
nGo = 10000;
go = randi(100, nGo, 1);
st = go + randi(100, nGo, 1);
nPoints = 10; %number of points in each row
tic
for ii = 1:100
A = nan(nGo, nPoints);
for iGo = 1:nGo
A(iGo,:) = linspace(go(iGo),st(iGo),nPoints); %create array of linearly spaced rows
end
end
t(1) = toc;
tic
for ii = 1:100
x = linspace(0,1,nPoints);
A2 = go + x.*(st - go);
end
t(2) = toc;
fprintf('Method 1: %.4f msec\nMethod 2: %.4f msec\nSpeedup: %.2f x\n', t*10, t(1)/t(2));
On my computer, I get:
Method 1: 9.6675 msec
Method 2: 0.0676 msec
Speedup: 143.07 x
Differences between A and A2 are on order of 1e-16.