Speeding up code by avoiding FOR, IF loops
조회 수: 13 (최근 30일)
이전 댓글 표시
Hi all, I have a question about how to speed up my code. I've been taught that for/if loops in matlab generally aren't great ideas, so I want to find a way to avoid them in the following code.
If you have suggestions on how to make these calculations outside of loops, I'd really appreciate it.
for i = 1:length(uniqueID)
for j = 1:length(timeList)
x = strmatch(uniqueID(i),idSeriesMonthly)
y = blsDataMonthly(x,[1 4])'
for k = 1:length(y)
if blsDataSeries(1,j) == y(1,k)
blsDataSeries(i + 1,j) = y(2,k)
end
end
end
end
댓글 수: 0
답변 (1개)
Jan
2012년 3월 3일
The rumor, that for-loops are slow in general concern the versions before 6.5 (July 2002). In modern Matlab versions the JIT can accelerate loops substantially.
In opposite to this strmatch is really slow. Better use strcmp or strncmp.
In addition the output to the command window consumes much time also. So append a semicolon after each assignment command.
You overwrite blsDataSeries(i + 1,j) repeatedly. So better start the innermost loop from the back and stop after the first match:
for k = length(y):-1:1
if blsDataSeries(1,j) == y(1,k)
blsDataSeries(i + 1,j) = y(2,k);
break; % Break out of the k-loop
end
end
Avoid the transposition of y.
[EDITED]
nTime = length(timeList);
blsDataSeries = zeros(length(uniqueID) + 1, nTime); % pre-allocate!
q = zeros(1, nTime);
for i = 1:length(uniqueID)
aID = uniqueID{i};
x = strncmp(aID, idSeriesMonthly, length(aID));
if sum(x) > 2
y1 = blsDataMonthly(x, 1);
y4 = blsDataMonthly(x, 4);
q(:) = NaN; % Re-use existing memory
for a = 1:length(y)
y1a = y1(a);
for b = nTime:-1:1
if y1a == timeList(b)
q(b) = y4(a);
break; % Break b-loop after the last occurrence
end
end
end
blsDataSeries(i + 1, :) = q;
end
end
댓글 수: 2
Jan
2012년 3월 4일
Is blsDataSeries pre-allocated properly? If not, this array grows in each iteration, which wastes a lot of time. See [EDITED]. It would be easier to help, if the types and sizes of the used variables are explained.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!