Question about 2D Vector Multiplication

1 回表示 (過去 30 日間)
mentalfiction
mentalfiction 2015 年 5 月 21 日
回答済み: James Tursa 2015 年 5 月 21 日
I just have a simple question about vector multiplication in MATLAB. Let's say I have these two vectors: A=[1 2 3 4 5] B=[6 7 8 9 1]
Now normally if you would multiply these you would get need to do a transpose of either one to get a dot product, however, I want to ask if it's possible to do something like the following:
Take the first value in Set A and multiply it once with each number in B (so on and so forth), to give something like:
6 12 18 .
7 14 21 .
8 16 24 .
9 18 27 .
1 2 3 etc
I'm sure there must be a simple way to do it but I can't figure it out and also possibly you can find a way to expand and do it manually, but a function would be ideal. I have 160 lines of code that I need to do this with. Help would be appreciated! Thank you!

採用された回答

Stephen23
Stephen23 2015 年 5 月 21 日
編集済み: Stephen23 2015 年 5 月 21 日
This is exactly what bsxfun is for:
>> A=[1 2 3 4 5];
>> B=[6 7 8 9 1];
>> X = bsxfun(@times,A,B(:))
X =
6 12 18 24 30
7 14 21 28 35
8 16 24 32 40
9 18 27 36 45
1 2 3 4 5
And if you want it all in one row (as your original example was) just wrap it in reshape like this:
>> X = reshape(bsxfun(@times,A(:),B),1,[])
X = 6 12 18 24 30 7 14 21 28 35 8 16 24 32 40 9 18 27 36 45 1 2 3 4 5
  2 件のコメント
mentalfiction
mentalfiction 2015 年 5 月 21 日
編集済み: mentalfiction 2015 年 5 月 21 日
Thank you so much! I'll test it out with my code now Really appreciate the help :)
Edit: It works with my code exactly how I wanted it to. Thanks once again!
Stephen23
Stephen23 2015 年 5 月 21 日
編集済み: Stephen23 2015 年 5 月 21 日
Glad to help!

サインインしてコメントする。

その他の回答 (1 件)

James Tursa
James Tursa 2015 年 5 月 21 日
This is a simple outer product. Depending on what order you want the results,
A.'*B
or
B.'*A

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by