如何在正常点和数组之间矢量化点积的总和

时间:2013-06-18 08:22:54

标签: matlab vector matrix vectorization dot-product

我需要评估以下表达式(伪数学表示法):

  

ipin

其中p是三元素向量的矩阵,n是三元素向量。我可以使用for循环执行此操作,但我无法弄清楚 如何对此进行矢量化:

p = [1 1 1; 2 2 2];
n = [3 3 3];
s = 0;
for i = 1:size(p, 1)
    s = s + dot(p(i, :), n)
end

3 个答案:

答案 0 :(得分:5)

为什么复杂化?简单矩阵乘法怎么样:

s = sum(p * n(:))

其中p被假定为 M -by-3矩阵。

答案 1 :(得分:0)

我认为你可以用bsxfun

来做到这一点
sum(sum(bsxfun(@times,p,n)))

答案 2 :(得分:0)

----------


% Is it the same for this case?


----------


n = 200;                  % depending on the computer it might be

m = 1000*n;               % that n needs to be chosen differently

A = randn(n,m);

x = randn(n,1);

p = zeros(m,1);

q = zeros(1,m);
tic;

for i = 1:m

    p(i) = sum(x.*A(:,i));
    q(i) = sum(x.*A(:,i));
end
time = toc; disp(['time = ',num2str(time)]);