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개)
참고 항목
카테고리
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!