How Can I replace the following for loop by vectorization?
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi Guys,
I have a set of large sparse matrices:
W ,size=(1,10,m)
V ,size=(10,1,m)
Y ,size=(10,10,n)
and I need the output matrix P as follow:
P(i,j)=W(:,:,i)*Y(:,:,j)*V(:,:,i)
e.g if m=2 & n=3
P=[
W(:,:,1)*Y(:,:,1)*V(:,:,1) W(:,:,1)*Y(:,:,2)*V(:,:,1);
W(:,:,1)*Y(:,:,2)*V(:,:,1) W(:,:,2)*Y(:,:,2)*V(:,:,2);
W(:,:,1)*Y(:,:,3)*V(:,:,1) W(:,:,2)*Y(:,:,3)*V(:,:,2)
]
I want to see if you have any suggestion how to write this by a single line code. I have written the code with "two for loop" but because of the large size of matrices, it is almost slow. Any faster idea is really appreciated.
Thank you in advance,
Alireza
댓글 수: 2
Jan
2016년 11월 22일
Please post your code and typical input data. It matters if m=1e3 and n=1e7 or the other way around. Perhaps your code is slow due to a forgotten pre-allocation.
What does "sparse" mean? Do the arrays contain a lot of zeros or do you sue the type sparse, which does not work for 3D-arrays?
채택된 답변
Roger Stafford
2016년 11월 23일
편집: Roger Stafford
2016년 11월 24일
Here's a single line code, but I'm not sure it's faster than, or even as fast as, your two nested for-loop solution:
Corrected:
P = (reshape(repmat(W,10,1,1).*repmat(V,1,10,1),[],m)).’*reshape(permute(Y,[2,1,3]),[],n);
댓글 수: 5
Roger Stafford
2016년 11월 24일
I'm glad to hear it. I was afraid it would be too slow. Sorry about the earlier error.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 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!