How to multiply each row of a matrix with a second full matrix, while applying a formula
1 回表示 (過去 30 日間)
古いコメントを表示
I want to multiply each row of 'a' into 'b' while applying a formula for each row of b, thus creating a new martix of size 8,4. Here is my code that's not working.
a=[3 4 5 1; 3 2 0 4]
b=[1 2 3 4;
2 0 2 4;
0 4 8 2;
2 1 0 4]
w=1
for s= 1:size(a,1)
for t= 1:size(b,1)
%updated formula%
new(w,:)= (3*a(1,1)+b(1,1)) + (5*a(1,2)+b(1,2)) +(a(1,3)+b(1,3)) + (5*a(1,4)+b(1,4)) %a formula
end
w=w+size(b,1)
end
1 件のコメント
採用された回答
その他の回答 (1 件)
Stephen23
2018 年 10 月 15 日
編集済み: Stephen23
2018 年 10 月 15 日
In just one line, works for any number of rows of a and b:
>> a = [3,4,5,1;3,2,0,4];
>> b = [1,2,3,4;2,0,2,4;0,4,8,2;2,1,0,4];
>> M = [3,5,1,5];
>> reshape(b.'+permute(M.*a,[2,3,1]),numel(M),[]).'
ans =
10 22 8 9
11 20 7 9
9 24 13 7
11 21 5 9
10 12 3 24
11 10 2 24
9 14 8 22
11 11 0 24
For MATLAB versions prior to R2016b you will need to use bsxfun for the + and the .* operations.
3 件のコメント
Stephen23
2018 年 10 月 29 日
編集済み: Stephen23
2018 年 10 月 29 日
"I mean, how do I read this?"
Break it down into its constituent parts, read the relevant documentation for those operators, and try some of their examples. It will help to print the intermediate arrays to see what values and shapes they have. You use the documentation and the examples to learn what those operators are doing, and why I combined them like that.
>> a = [3,4,5,1;3,2,0,4];
>> b = [1,2,3,4;2,0,2,4;0,4,8,2;2,1,0,4];
>> M = [3,5,1,5];
>> M.*a % M times a (note the scalar dimension expansion)
ans =
9 20 5 5
9 10 0 20
>> permute(M.*a,[2,3,1]) % rearrange dimensions [1,2,3] -> [2,3,1]
ans(:,:,1) =
9
20
5
5
ans(:,:,2) =
9
10
0
20
>> b.' % transpose b
ans =
1 2 0 2
2 0 4 1
3 2 8 0
4 4 2 4
>> b.'+permute(M.*a,[2,3,1]) % add (note the scalar dimension expansion)
ans(:,:,1) =
10 11 9 11
22 20 24 21
8 7 13 5
9 9 7 9
ans(:,:,2) =
10 11 9 11
12 10 14 11
3 2 8 0
24 24 22 24
>> reshape(b.'+permute(M.*a,[2,3,1]),numel(M),[]) % reshape
ans =
10 11 9 11 10 11 9 11
22 20 24 21 12 10 14 11
8 7 13 5 3 2 8 0
9 9 7 9 24 24 22 24
>> reshape(b.'+permute(M.*a,[2,3,1]),numel(M),[]).' % transpose
ans =
10 22 8 9
11 20 7 9
9 24 13 7
11 21 5 9
10 12 3 24
11 10 2 24
9 14 8 22
11 11 0 24
The documentation explains permute, reshape, times, and transpose. Try their examples to learn more about them.
Two important things to remember:
- MATLAB works columnwise, which is why I had to transpose b and the final matrix.
- For MATLAB versions R2016b+ many operators expand scalar dimensions to match the other input arguments (earlier versions will need to use bsxfun). Learn more:
参考
カテゴリ
Help Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!