What is the most effieicnt method of multiplying a 2d matrix by a vector to give a 3d matrix?
조회 수: 1 (최근 30일)
이전 댓글 표시
I want to create a 3D matrix by multiplying all the elements in a 2d matrix by all the elements in a vector to give a 3d matrix.
I initially used this: x=3; y=3; z=4;
flat = [1,2,3;4,5,6;7,8,9];
deep = [1,2,3,4]';
field=zeros(3,3,4);
tic
for i=1:x
for j=1:y
field(i,j,:)=flat(i,j)*deep;
end
end
toc
Elapsed time is 0.000027 seconds.
but thought I could speed it up if I replaced the loop with:
tic
for i=1:z
field(:,:,i) = flat(:,:)*deep(i);
end
toc
Elapsed time is 0.000202 seconds. However, the first method with more loop iterations proved faster. Can anyone explain why and more importantly is there a better, more effieint method than either of these?
Thanks
댓글 수: 0
답변 (1개)
Matt J
2012년 11월 23일
편집: Matt J
2012년 11월 23일
For larger data, you'll probably find this version the most efficient
field = bsxfun(@times, flat, reshape(deep,1,1,[]) );
However, the first method with more loop iterations proved faster.
First, the data is way too small for this to be a good test of anything. However, I think the main reason the 2nd version is slower is because you are indexing flat(:,:) unnecessarily. When I modify to
field(:,:,i) = flat*deep(i);
the 2nd version becomes faster for me.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!