Is there a better vectorization technique?
Show older comments
I am trying to see if there are other ways of coding this code sample more efficiently. Here, y is an 1xM matrix, (say, 1x1000), and z is an NxM matrix, (say, 5x1000).
mean(ones(N,1)*y.^3 .* z,2)
This code works fine, but I worry of N increases a lot, that the:
ones(N,1)*y.^3
might get too wasteful and make everything slow down.
Thoughts?
Accepted Answer
More Answers (1)
The power() operator is more expensive than the matrix multiplication. Therefore an explicit multiplication saves time:
M = 1000;
N = 5;
y = rand(1, M);
z = rand(N, M);
tic; for i=1:100, a = mean(ones(N,1) * y .^ 3 .* z, 2); end; toc
% Elapsed time is 0.036668 seconds.
tic; for i=1:100, a = z * y.' .^ 3 / M; end; toc
% Elapsed time is 0.026818 seconds.
tic; for i=1:100, a = z * (y .* y .* y)' / M; end; toc
% Elapsed time is 0.001327 seconds.
[EDITED] If the resulting array is very large, a multiplication is faster than a division, but the result can differ due to rounding:
a = z * (y .* y .* y)' * (1 / M);
For the small [5x1] array in the example this does not matter.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!