bsxfun vs for loop. Code Optimization.

3 ビュー (過去 30 日間)
Daniel Pereira
Daniel Pereira 2014 年 4 月 28 日
編集済み: Star Strider 2014 年 4 月 29 日
Hello everyone.
I'm trying to optimize some code that is running in a for loop. The code is the following:
for k=...
n=20;
u = rand(4386,21,n);
v = rand(size(u(:,:,1)));
F = zeros(size(u,1),n);
for m=1:n
F(:,m) = squeeze(max(u(:,:,m).*v,[],2));
end
output(k) = function(F);
end
I've tried replacing the inner for loop by bsxfun , this way:
for k=...
n=20;
u = rand(4386,21,n);
v = rand(size(u(:,:,1)));
F = squeeze(max(bsxfun(@times,u,v),[],2));
output(k) = function(F);
end
But bsxfun is taking more time than the previous solution.
Why is that happening?
Any other ideas to optimize this code?
I'm working with the specified dimensions, and the bottleneck of the problem is located in the creation of array F .
Thanks in advance.
Dani

採用された回答

Star Strider
Star Strider 2014 年 4 月 28 日
If I understand bsxfun correctly, it’s taking longer because it’s expanding v to multiply elements of v by every element of u, not simply the 3rd dimension.
From the documentation:
Whenever a dimension of A or B is singleton (equal to one), bsxfun virtually replicates the array along that dimension to match the other array.
  2 件のコメント
Daniel Pereira
Daniel Pereira 2014 年 4 月 29 日
The thing is that v is [4836×21], so I understand that bsxfun is only expanding the third dimension, that is the first singleton dimension that does not match the dimension of u.
I think the two algorithms are doing the same, since both give the same result for F.
Thank you anyway.
Star Strider
Star Strider 2014 年 4 月 29 日
編集済み: Star Strider 2014 年 4 月 29 日
They’re both doing the same on the dimensions of interest to you, with bsxfun doing it on the third dimension as well, making it slower. They would give you the same result, because you’re only looking at some of the dimensions of F. The bsxfun function is just doing what you asked it to.
My pleasure!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLinear Least Squares についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by