How to vectorize loop with linspace for performance
3 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
Joseph Cheng
2015-12-11
编辑:Joseph Cheng
2015-12-11
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 个评论
Joseph Cheng
2015-12-11
编辑:Joseph Cheng
2015-12-11
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)]);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!