how to vectorize the following code?

조회 수: 2 (최근 30일)
UCL student
UCL student 2014년 10월 23일
댓글: Star Strider 2014년 10월 23일
Could anyone explain the steps?
DelayStep = 60;%in seconds
MaxStep = 86400;
for j=dStart:dEnd
currDay = datevec(j);
for k=0:DelayStep:MaxStep
hms = [0 0 0 fix(mod(k, [0, 3600, 60]) ./ [3600, 60, 1])];
UTCTimetoCalculate = datestr(hms+currDay);
end
end
  댓글 수: 2
Patrik Ek
Patrik Ek 2014년 10월 23일
Well, what have you tried? How about vectorizing k for the innermost loop by the way?
UCL student
UCL student 2014년 10월 23일
I tried this in the inner section, but it doesn't seem to work:
k=0:DelayStep:MaxStep
hms = [0 0 0 fix(mod(k(:), [0, 3600, 60]) ./ [3600, 60, 1])];
UTCTimetoCalculate = datestr(hms+currDay)

댓글을 달려면 로그인하십시오.

채택된 답변

Star Strider
Star Strider 2014년 10월 23일
You can replace the inner ‘k’ loop with:
currDay = datevec(j);
hms = bsxfun(@plus, currDay, zeros(1440,6));
hms(:,5) = 1:1440;
TCTimetoCalculate = datestr(datenum(hms));
since you are actually incrementing every minute (with 1440 minutes/day)|.
  댓글 수: 2
UCL student
UCL student 2014년 10월 23일
It looks good, thanks. But how to vectorize the outer part?
Star Strider
Star Strider 2014년 10월 23일
This will work, assuming I understand what you want to do. You can vectorise both loops in four statements:
dStart = datenum(now);
dEnd = datenum(now+7); % Spans One Week
Minutes = fix(dEnd-dStart+1)*1440;
hms = bsxfun(@plus, datevec(dStart), zeros(Minutes,6));
hms(:,5) = 1:Minutes;
TCTimetoCalculate = datestr(datenum(hms));
I created ‘dStart’ and ‘dEnd’ to test it, and it works assuming they are both date numbers. If they aren’t convert them to date numbers to use my code.
To be sure it is producing the results you want, this line lets you look at the first five and last five entries of ‘TCTimetoCalculate’:
TCTimetoCalculate([1:5 end-5:end],:)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by