multiply element of a row vector (A) by corresponding row of matrix (B) and sum

1 回表示 (過去 30 日間)
Isma
Isma 2015 年 9 月 3 日
コメント済み: Matt J 2015 年 9 月 3 日
Hi
I am currently looking for an assistance on the way to perform such calculation:
A=[0 1 2 3];B=[1 2;3 4;5 6;7 8];
0*1 + 0*2
C= 1*3 + 1*4
2*5 + 2*6
3*7 + 3*8
==> C=[0;7;22;45]
I had a look at
bsxfun(@times,,)
but it can't be useful here (unfortunately).
Best,

採用された回答

Star Strider
Star Strider 2015 年 9 月 3 日
This works:
C = sum(bsxfun(@times, A', B),2);
To get bsxfun to work here, you have to transpose ‘A’ so that the two arguments have a dimension in common. Then sum across the columns (dimension 2).
  2 件のコメント
Isma
Isma 2015 年 9 月 3 日
Thanks a lot for the hint regarding the transpose of A. Cheers.
Star Strider
Star Strider 2015 年 9 月 3 日
My pleasure.

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

その他の回答 (1 件)

Matt J
Matt J 2015 年 9 月 3 日
C=A(:).*sum(B,2);
  2 件のコメント
Isma
Isma 2015 年 9 月 3 日
Thanks a lot too. It's indeed interesting to know alternative solutions. Cheers.
Matt J
Matt J 2015 年 9 月 3 日
I had a look at bsxfun(@times,,) but it can't be useful here (unfortunately).
It's actually fortunate that you can avoid bsxfun. If B is an M x N matrix, then using bsxfun will require M*N multiplications, whereas with what I propose, you only do M multiplications.

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

カテゴリ

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