How to vectorize loop with linspace for performance

2 Ansichten (letzte 30 Tage)
T
T am 10 Dez. 2015
Bearbeitet: Joseph Cheng am 11 Dez. 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

Antworten (1)

Joseph Cheng
Joseph Cheng am 11 Dez. 2015
Bearbeitet: Joseph Cheng am 11 Dez. 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.
  1 Kommentar
Joseph Cheng
Joseph Cheng am 11 Dez. 2015
Bearbeitet: Joseph Cheng am 11 Dez. 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)]);

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by