Vectorisation of for loops
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Jan
el 11 de Sept. de 2012
@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. :-)
Respuestas (2)
Sean de Wolski
el 11 de Sept. de 2012
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 comentarios
Jan
el 11 de Sept. de 2012
Editada: Jan
el 11 de Sept. de 2012
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 comentarios
Jan
el 12 de Sept. de 2012
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
el 12 de Sept. de 2012
That would be my first recommendation: replace every repmat with the corresponding bsxfun.
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!