Vectorisation of for loops

1 回表示 (過去 30 日間)
Alex Gregory
Alex Gregory 2012 年 9 月 11 日
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 件のコメント
Alex Gregory
Alex Gregory 2012 年 9 月 11 日
Delta approximates the value of Delta for an Asian option. It does this for i=1 to Days=(3*365) over k=1 to Sims=1000.
As i increases 1 day less of volatility and daily weightings are needed for the calculation as there are Days-i days remaining until the option expires.
Jan
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
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)

Jan
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
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
Sean de Wolski 2012 年 9 月 12 日
That would be my first recommendation: replace every repmat with the corresponding bsxfun.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by