# How to vectorize loop with linspace for performance

3 views (last 30 days)
T on 10 Dec 2015
Edited: Joseph Cheng on 11 Dec 2015
Besides prelocation my matrix A, how can I save time here?
for k=1:1:10000 A(k,:)=firstValue(k):fixedStep:lastValue(k); end
Basically I have a matrix and each row is a series of values with equidistant distance. But the firstValue differs and is saved in array firstValue

Joseph Cheng on 11 Dec 2015
Edited: Joseph Cheng on 11 Dec 2015
Well... you can speed this up by performing the following.
clc
clear all
fV = [1:10];
lV = [1001:1010];
fixedStep=.0001;
tic,
for k=1:1:10
A(k,:)=fV(k):fixedStep:lV(k);
end
original = toc;
disp(['original time= ' num2str(original)]);
tic,
B = zeros(size(A));
for k=1:1:10
B(k,:)=fV(k):fixedStep:lV(k);
end
preAllocated = toc;
disp(['preallocated time= ' num2str(preAllocated)]);
tic
C=zeros(size(A)); %preallocate C
Numsteps = (lV(1)-fV(1))/fixedStep+1; %determine total number of steps
steps = repmat(fixedStep*[0:Numsteps-1],10,1); %create a matrix of incr. steps
C = steps+repmat(fV',1,Numsteps); % add steps matrix to first value column
unnamed = toc;
disp(['no idea what this is called time= ' num2str(unnamed)]);
Now there is some issue with that last method which I can't really think of a name for it but there is some floating point error in it. you can check this with
MaxFPerror = max(abs(C(:)-A(:)))
which for me was 1.13*10^-13 max error.
Joseph Cheng on 11 Dec 2015
Edited: Joseph Cheng on 11 Dec 2015
oh and using linspace wouldn't speed it up but to do it you'd use something like:
tic
D=zeros(size(A)); %preallocate D
Numsteps = (lV(1)-fV(1))/fixedStep+1; %determine total number of steps
for k=1:1:10
D(k,:) = linspace(fV(k),lV(k),Numsteps);
end
usingLinspace= toc;
disp(['using linspace= ' num2str(usingLinspace)]);