如何有效地对10对阵列进行矩阵乘法并对乘法矩阵的相应结果求和?例如:
创建两个数组,A1和B1。
A1 = [1 3 5; 2 4 7];
B1 = [-5 8 11; 3 9 21; 4 0 8];
计算A1和B1的乘积。
C1 = A1*B1
C1 =
24 35 114
30 52 162
创建另外两个数组,A2和B2。
A2 = [7 9 11; 3 5 6];
B2 = [-1 2 3; 4 5 6; 4 1 8];
计算A2和B2的乘积。
C2 = A2*B2
sum_of_products1 = sum(C1,C2);
sum_of_products2 = sum(C3,C4); and so on till
.
.
.
sum_of_products5 = sum(C9,C10);
更新
根据回复,我输入了矢量。总结的结果是不正确的。
clc;
clear all;
%VECTORS
A1(:,1) = [1 2 3 4].';
A1(:,2) = [5 6 7 8].';
%// Concatenate all An and Bn arrays along third dim to have A, B as 3D arrays
A = cat(3,A1(:,1),A1(:,2));
B = cat(3,A1(:,1)',A1(:,2)');
%// You may clear A1, A2,...A10, B1, B2.., B10 at this point for a cleaner workspace
%// Get the product values into a 3D array
multvals = squeeze(sum(bsxfun(@times,permute(A,[1 2 4 3]),permute(B,[4 1 2 3])),2))
%// Finally get the sum of product values
sumvals = squeeze(sum(reshape(multvals,size(A,1),size(A,2),2,[]),3))
答案
多个人(:,:,1)=
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
多个人(:,:,2)=
25 30 35 40
30 36 42 48
35 42 49 56
40 48 56 64
sumvals =
3 7 55 75
6 14 66 90
9 21 77 105
12 28 88 120
正确的答案应该是
s1 = multvals(:,:,1);
s2 = multvals(:,:,2);
sumvals = s1 + s2;
sumvals =
26 32 38 44
32 40 48 56
38 48 58 68
44 56 68 80
答案 0 :(得分:2)
您可以将它们连接成两个3D数组并使用它们,而不是遍历所有这些数组。
%// Concatenate all An and Bn arrays along third dim to have A, B as 3D arrays
A = cat(3,A1,A2,...)
B = cat(3,B1,B2,...)
%// You may clear A1, A2,..., B1, B2..., at this point for a cleaner workspace
%// Get the product values into a 3D array
multvals = sum(bsxfun(@times,permute(A,[1 2 4 3]),permute(B,[4 1 2 3])),2)
%// Finally get the sum of product values
[m1,m2,m3,m4] = size(multvals);
sumvals = squeeze(sum(reshape(multvals,m1,m2,m3,2,[]),4))
multvals
的最后一个维度中的每个切片都对应于这些C
数组中的每一个。最后,3D
的每个sumvals
切片都对应于每个sum_of_products
数组。
1)矢量案例
clear all;clc;
%// VECTORS
A1 = [1 2 3 4].';
B1 = [5 6 7 8];
A2 = [11 12 13 14].';
B2 = [15 16 17 18];
A = cat(3,A1,A2);
B = cat(3,B1,B2);
multvals = sum(bsxfun(@times,permute(A,[1 2 4 3]),permute(B,[4 1 2 3])),2);
[m1,m2,m3,m4] = size(multvals);
sumvals = squeeze(sum(reshape(multvals,m1,m2,m3,2,[]),4))
solution_with_approach_from_question = A1*B1 + A2*B2
%// this should yield values identical to sumvals(:,:,1)
输出 -
sumvals =
170 182 194 206
190 204 218 232
210 226 242 258
230 248 266 284
solution_with_approach_from_question =
170 182 194 206
190 204 218 232
210 226 242 258
230 248 266 284
2)矩阵案例
clear all;clc;
%// MATRICES
A1 = [1 3 5; 2 4 7];
B1 = [-5 8 11; 3 9 21; 4 0 8];
A2 = [7 9 11; 3 5 6];
B2 = [-1 2 3; 4 5 6; 4 1 8];
A = cat(3,A1,A2);
B = cat(3,B1,B2);
multvals = sum(bsxfun(@times,permute(A,[1 2 4 3]),permute(B,[4 1 2 3])),2);
[m1,m2,m3,m4] = size(multvals);
sumvals = squeeze(sum(reshape(multvals,m1,m2,m3,2,[]),4))
solution_with_approach_from_question = A1*B1 + A2*B2
%// this should yield values identical to sumvals(:,:,1)
输出 -
sumvals =
97 105 277
71 89 249
solution_with_approach_from_question =
97 105 277
71 89 249