Vectorisation of for loops
조회 수: 1 (최근 30일)
이전 댓글 표시
Being fairly new to Matlab and the concept of vectorisation rather than iteration I need some help getting my head around avoiding for loops.
I'd like to use arrayfun but don't know how to implement it with changing parameter dimensions.
Nested for loop
for k = 1:Sims
for i = 1:Days
Hist = sum(Weights(1:i,1) .* FF(1:i,k));
Deltas(i,k) = Delta(FF(i,k), Hist, v(i:end), 60.64633, Weights(i:Days), 2500, Days-i);
end
end
Notice that v and Weights dimensions decreases as i increases, and the last parameter passed to Delta (Days) is decreased in size by i.
Any thoughts, can it even be done?
댓글 수: 3
Jan
2012년 9월 11일
@Alex: A cute answer. The meaning of the values is not important, only the type and size or if it is an array or a function. :-)
답변 (2개)
Sean de Wolski
2012년 9월 11일
arrayfun is slow and difficult to use/read. It has really no advantages. I do not know why you would want to use it over the for-loops. If you preallocate Deltas that will help with speed. Using arrayfun will hurt and make your code harder to understand.
Before the loop:
Deltas = zeros(Sims,Days)
댓글 수: 0
Jan
2012년 9월 11일
편집: Jan
2012년 9월 11일
At least calculating the sum repeatedly can be avoided:
Deltas = zeros(Days, Sims);
for k = 1:Sims
Hist = cumsum(Weights(:, 1) .* FF(:, k));
for ii = 1:Days
Deltas(ii,k) = Delta(FF(i,k), Hist(ii), v(ii:end), 60.64633, Weights(ii:Days), 2500, Days-ii);
end
end
If you post the code of "Delta" further improvements are possible.
댓글 수: 3
Jan
2012년 9월 12일
Obviously the main part of the program happens inside the function Delta(). Then the outer loop is most likely negligible.
If you provide some sample data, e.g. created by RAND(), such that we can tun your program, it would be easier to test modifications. I assume the REPMAT waste a lot of time here and some BSXFUN would be remarkably faster.
Sean de Wolski
2012년 9월 12일
That would be my first recommendation: replace every repmat with the corresponding bsxfun.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!