フィルターのクリア

What is the most effieicnt method of multiplying a 2d matrix by a vector to give a 3d matrix?

1 回表示 (過去 30 日間)
Simon
Simon 2012 年 11 月 23 日
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

回答 (1 件)

Matt J
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.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by