フィルターのクリア

How to vectorize the loops

1 回表示 (過去 30 日間)
Yeping Sun
Yeping Sun 2016 年 9 月 22 日
編集済み: Andrei Bobrov 2016 年 9 月 22 日
Dear all,
Could anyone tell me how to vectorize the follow loops:
Best regards.
Yeping Sun
  4 件のコメント
Yeping Sun
Yeping Sun 2016 年 9 月 22 日
編集済み: Yeping Sun 2016 年 9 月 22 日
The code I mean should be:
for i=1:1:40
for j=1:1:40
for k=1:1:5596
Hr(i,j)=sum(delta_2(k,i,j)*exp(dv(k));
end
end
end
delta is a (5596x40x40) matrix,dv is a 5596-element vector. The attached test.mat file contains these two entities.
What I want to do is to multiple an exponent factor (exp(dv)) to each element of the first dimension of the 3D matrix delta_2 and then sum them up, and the sums are assigned as the element of the result Hr matrix (40x40).
Now I have two questions: (1) it takes over 8000 s for the code to finish the calculation in my computer, which is too long; (2)the elements in dv are too large and exp(dv) cannot be properly calculated in matlab. Would you minding helping me solve these questions?
Warm regards.
Yeping Sun
Andrei Bobrov
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
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,[]);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by