我有三个向量a,b和c。 a_i的值取决于向量b和c的所有值的笛卡尔积的和,它再次乘以三维矩阵w的因子:
如何在Matlab中编写?
答案 0 :(得分:1)
让b, c
成为列向量。最简单的方法是将w
折叠为二维矩阵,然后乘以b
,如下所示:
w2 = sum(bsxfun(@times,w,shiftdim(c,-2)),3);
a = w2 * b;
这里我测试了随机数据的语法错误:
n = 10;
w = randn(n,n,n);
b = randn(n,1);
c = randn(n,1);
w2 = sum(bsxfun(@times,w,shiftdim(c,-2)),3);
a = w2 * b;
% using loops:
aalt = zeros(n,1);
for ii=1:n
for jj=1:n
for kk=1:n
aalt(ii,1) = aalt(ii,1) + w(ii,jj,kk) * b(jj) * c(kk);
end
end
end
% up to roundoff error:
max(abs(aalt - a))
答案 1 :(得分:1)
a = sum(sum(bsxfun(@times, w, shiftdim(bsxfun(@times, b(:), c(:).'), -1)), 3), 2)
或者用矩阵乘法替换内部bsxfun
:
a = sum(sum(bsxfun(@times, w, reshape(b(:)*c(:).',[1 numel(b) numel(c)])), 3), 2)