How to vectorize the loops
古いコメントを表示
Dear all,
Could anyone tell me how to vectorize the follow loops:

Best regards.
Yeping Sun
4 件のコメント
Andrei Bobrov
2016 年 9 月 22 日
What is it - dv? Scalar or vector?
Jan
2016 年 9 月 22 日
The EXP function is very expensive. It seems in your example like you apply it for a constant repeatedly. The inner loop overwrites the value of Hr(i,j) 5596 times, so you can easily get a speedup of factor 5596 if you omit the loop over k.
Is Hr pre-allocated before the loops?
Summary: It is hard to optimize code, which is shown partially only. Better post the real code together with some test data.
Yeping Sun
2016 年 9 月 22 日
編集済み: Yeping Sun
2016 年 9 月 22 日
Andrei Bobrov
2016 年 9 月 22 日
編集済み: Andrei Bobrov
2016 年 9 月 22 日
Your code should be:
ev = exp(dv(:))';
Hr = zeros(40,40);
for ii = 1:40
for jj = 1:40
Hr(ii,jj) = ev*delta_2(:,ii,jj);
end
end
Vectorize form see my answer in part 3.
回答 (1 件)
Andrei Bobrov
2016 年 9 月 22 日
編集済み: Andrei Bobrov
2016 年 9 月 22 日
if dv -scalar:
out = permute(sum(delta*exp(dv)),[2,3,1]);
if dv - vector:
out = permute(sum(...
reshape(sum(bsxfun(@plus,reshape(delta,[],1),exp(dv(:)')),2),size(delta))...
),[2,3,1]);
part 3
ev = exp(dv)';
[~,n,k] = size(delta_2);
out = reshape(ev*reshape(delta_2,k,[]),n,[]);
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!