Getting rid of a loop
조회 수: 4 (최근 30일)
이전 댓글 표시
Hi,
I have a loop that takes forever. I am wondering if i can get rid of it by using a one step procedure
[yd,md,dd]=datevec(RSSD9999d);%RSSD9999d is the dates vector for my sample
[y,m,~]=datevec(RSSD9999);% RSSD9999 is the dates vector from the database > sample size
for i=1:length(RSSD9001d)% I am running the loop to compute the previous 3 year historical average
x0=find(RSSD9001==RSSD9001d(i) & ismember(RSSD9999,[datenum(yd(i)-3,md,dd):RSSD9999d(i)-1]));
% the minus one is not a mistake, the data has the form year, then quarter (could be 3,6,9,or 12), then day
% by putting minus 1 i ensure that the 3 year average will not include the current date
EquityCapitalgta = RCFD3210(x0)./GTA(x0);
EquityCapital_GTAavg3y(i,1)=nanmean(EquityCapitalgta);
end
댓글 수: 0
채택된 답변
Jan
2016년 11월 10일
편집: Jan
2016년 11월 10일
Did you pre-allocate the output?
EquityCapital_GTAavg3y = zeros(1, length(RSSD9001d))
Use the profiler to find out, how many time is spent in datenum . If this matters, replace it.
ismember sorts its inputs. Try to sort it at first an call ismembc (see code of ismember.
This part:
ismember(RSSD9999,[datenum(yd(i)-3,md,dd):RSSD9999d(i)-1]))
might be accelerated by:
RSSD9999>=datenum(yd(i)-3,md,dd) && RSSD9999 <= RSSD9999d(i)-1
The names of your variables are horrifying. It is really hard to read your code. Note that a working algorithm does not depend on the meaning of the variables, so you could use some leaner names.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!