我需要评估以下表达式(以伪数学表示法):
∑<sub>ipi⋅<b>n
其中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
我需要评估以下表达式(以伪数学表示法):
∑<sub>ipi⋅<b>n
其中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
Why complicate things? How about simple matrix multiplication:
s = sum(p * n(:))
where p
is assumed to be an M-by-3 matrix.
I think you can do it with bsxfun
:
sum(sum(bsxfun(@times,p,n)))
----------
% 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)]);