element wise multiplication and sum

22 ビュー (過去 30 日間)
Kaushik
Kaushik 2012 年 12 月 3 日
コメント済み: Yency Perez 2020 年 9 月 10 日
hi,
i have a matirx a = [1,2,3;4,5,6]; and another matrix b=[2,2,2]
i want to multiply a[i,:].*b where i=1,2 (i.e. the rows of matrix a).
this will result in a matrix y with two rows (with 15 in row1 and 30 in row2)
how do i achieve this efficently without writing a "for" loop.
thanks in advance
  1 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 12 月 3 日
What is the expected result?

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

採用された回答

Matt Fig
Matt Fig 2012 年 12 月 3 日
編集済み: Matt Fig 2012 年 12 月 3 日
I don't know where the 15 came from. I assume you mean 12.
>> a = [1,2,3;4,5,6];
>> b = [2,2,2];
>> a*b.' % same results as: sum(a.*[b;b],2)
ans =
12
30
  2 件のコメント
Evan
Evan 2012 年 12 月 3 日
Oh wow, I can't believe I missed that. Yes, this is a much better answer. :P
Yency Perez
Yency Perez 2020 年 9 月 10 日
Hi, i'm wondering how to do it using a "for" loop!

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

その他の回答 (2 件)

Akbar Khan
Akbar Khan 2016 年 8 月 20 日
As per my understanding of internal implementation of matlab. Matrix multiplication and matrix addition is an O(n^3) and O(n^2) time complexity algorithm. However I am not sure whether Strassen's algorithm is implemented internally.

Evan
Evan 2012 年 12 月 3 日
編集済み: Evan 2012 年 12 月 3 日
NOTE: Ignore my answer. Matt's is much better. :P
>> a = [1,2,3;4,5,6]; >> b = [2,2,2]; >> tic >> c = bsxfun(@times,a,b) >> toc
c =
2 4 6
8 10 12
Elapsed time is 0.000333 seconds.
For more info:
help bsxfun
Another (faster) way would be to resize b to be the same size as a and then perform element-wise multiplication. So something like this:
>> a = [1,2,3;4,5,6];
>> b = [2,2,2];
>> n = 2; %OR n = size(a,1);
>> tic
>> c = a .* b(ones(n,1),:) %second term is same as (ones(n,1) * b)
>> toc
  c =  
2     4     6
       8    10    12
Elapsed time is 0.000040 seconds.
You would just have to find the number of rows in a and use that as n for a general case.
Then, of course, you would just use the "sum" function to get your answer. I'm guessing you meant you wanted your answer to be [12; 30]? If so, you would just sum along columns:
>> y = sum(c,2)
y =
12
30

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by