1

我尽我所能不使用循环。但是我发现除了使用循环之外很难解决它。是否可以矢量化循环代码?谢谢

a=[0.1361,0.8530,0.0760;0.8693,0.6221,0.2399;0.5797,0.3510,0.1233;.5499,0.5132,0.1839; 0.1450,0.4018,0.2400];
b=[0.4173,0.4893,0.7803;0.0497,0.3377,0.3897;0.9027,0.9001,0.2417;0.9448,0.3692,0.4039;0.4909,0.1112,0.0965];
[m1,n1,l]=size(a);
awe=-0.5;
g = [81.2379 92.4675;92.4675 118.1451];
ver=inv(g);
p=zeros(m1,n1);
for i=1:m1
for j=1:n1
    CD=[a(i,j) ; b(i,j)]
    p(i,j)= CD'*ver* CD;
end
end
q = exp(awe*p);
4

2 回答 2

3

好吧,将矩阵p分解为多个组件允许您通过以下方式对计算进行矢量化:

p = a .^ 2 * ver(1, 1) + a .* b * (ver(1, 2) + ver(2, 1)) + b .^ 2 * ver(2, 2);

或者,您可以像这样概括解决方案:

CD = [a(:), b(:)]';
p = reshape(diag(CD' * ver * CD), size(a));

请注意,这是一个稍慢的解决方案。

于 2013-03-04T17:32:27.130 回答
1

当然你可以做到。

CD = reshape(diag([a(:),b(:)]*ver*[a(:),b(:)]'),5,3);

但只有对角线

[a(:),b(:)]*ver*[a(:),b(:)]' 

是需要的。

所以更换

diag([a(:),b(:)]*ver*[a(:),b(:)]')

和:

sum(  [a(:),b(:)]'  .*  (ver*[a(:),b(:)]') , 1)'
于 2013-03-04T17:32:12.513 回答