How to vectorize loop with linspace for performance
조회 수: 2 (최근 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!