如何获得没有循环的加权矩阵的均值?

时间:2017-02-04 18:08:00

标签: matlab matrix matrix-multiplication vector-multiplication

我有一组标量和矩阵:

w1, w2...wn
A1, A2... An

如何获得

w1*A1 + w2*A2 + ... + wn*An

没有循环? 以及如何有效地获得

w1*(b1*c1) + w2*(b2*c2) + ... + wn*(bn*cn)

bici是向量,但bi*ci是矩阵,而不是标量?

2 个答案:

答案 0 :(得分:0)

修改:我有更好的解决方案。

如果您的矩阵An存储在大小为P x Q x N的3-D矩阵中,An = A(:,:,n)n = 1, 2, ..., N,并且您的权重存储在权重向量w中大小1 x N然后以下命令执行加权平均值:

B = reshape(w*reshape(permute(A,[3,1,2]),N,[]),[P,Q]);

答案 1 :(得分:0)

bsxfun可以通过以下方式解决第一个问题:

% create matrices
a=[1 2]
b=randi(9,[3 3 2])

% now you will have to reshape a, so that its non-singleton dimensions match b
% i.e. a is 1 x 2 and b is 3 x 3 x 2, so second dimension of (=2) should match 
% 3rd dimension of b (=2). Thus a should be of shape `1 x 1 x 2`. Then you can 
% multiply using bsxfun and sum along 3rd dimension as follows

sum(bsxfun(@times, permute(a,[3 1 2]), b),3)