how do I vectorize a loop with multi-dimensional arrays/ outer product
1 回表示 (過去 30 日間)
古いコメントを表示
Hi, would someone happen to know how I could vectorize the following loop?
L=4;
for t=1:N;
A(:,:,t)=exp(a*(t-1)).*B(:,:,L);
end
many thanks, Eli
採用された回答
Andrei Bobrov
2013 年 6 月 21 日
B1 = B(:,:,4);
out = reshape(B1(:)*(0:N-1),[size(B1) N]);
3 件のコメント
James Tursa
2013 年 6 月 22 日
編集済み: James Tursa
2013 年 6 月 22 日
Your timing is comparing apples to oranges. You preallocate the answer for your loop but do not include it in your timing, whereas you penalize the reshaped outer product by including its intrinsic allocation in the timing. Your loop timing should be this instead, which includes both the allocation and the operations:
tic
C=NaN(128,256,N);
for t=1:N
C(:,:,t)=B(:,:,4)*a(t);
end
toc
Also, the timings should be run several times to make sure background functions are loaded into memory (I assume you do not want the function loading times to bias your results). So don't clear all between timing runs, just clear the variables you allocate (e.g., C, B1, and C1).
その他の回答 (1 件)
Iain
2013 年 6 月 21 日
編集済み: Iain
2013 年 6 月 21 日
A = bsxfun(@times,exp(bsxfun(@times,a,0:(t-1)),B);
You need to make sure that a, 0:t-1 and B are all in the correct dimensions, and that "times", is the correct multiplication for your needs.
A = bsxfun(@times,exp(bsxfun(@times,a,reshape(0:(t-1),1, 1,[]),B);
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!