Alternative to reshape to multiply multidimensional arrays
8 views (last 30 days)
Show older comments
I am working on a dynamic programming problem and after profiling my code I noticed that most of the computing time is spent using the reshape function to quickly multiply a value function by a probability array. This is faster than using for loops but not fast enough. The line using the reshape function takes almost 50% of the total computation time. Any suggestions would be very appreciated. Please let me know if the description/code is not clear. Thank you.
no_obs = 210;
EV = zeros(no_obs,4);
next_age = [9;1;1;1];
Vinit(pr1,pr2,pr3,next_age,action,no_obs)
for action=1:4
V = reshape(Vinit(:,:,:,next_age(action),action,:),[],no_obs);
EV(:,action)=(P_array(:).' * V).';
end
0 Comments
Accepted Answer
Walter Roberson
on 7 Mar 2013
Edited: Walter Roberson
on 7 Mar 2013
NV = permute(Vinit, [1 2 3 6 4 5])
before you start, so that when you fill in the next_age(action) and action subscripts, you are taking a slice of contiguous memory NV(:,:,:,:, next_age(action), action).
Filling in the actual value for [] is measurably faster.
You might possibly get better performance by
NV = permute(Vinit, [6 1 2 3 4 5]);
and then
EV(:,action) = reshape( NV(:,:,:,:, next_age(action), action), no_obs, [] ) * P_array(:);
(except fill in [] with the actual value for better performance)
Especially if you can go back and create the Vinit in that order instead of permute()'ing it.
2 Comments
Walter Roberson
on 7 Mar 2013
Also, you can do the P_array(:) before the loop and assign it into a variable.
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!