yoname
yoname

Reputation: 11

Vectorizing Matlab Loops

I Im trying my best not to use loops. But I find it very difficult to solve it other than using loops. Is it possible to vectorize the loop code?Thanks

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);

Upvotes: 1

Views: 197

Answers (2)

Eitan T
Eitan T

Reputation: 32930

Well, breaking matrix p down into multiple components allows you to vectorize the computation in the following way:

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

Alternatively, you can generalize the solution like so:

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

Note that this is a slightly slower solution though.

Upvotes: 3

Min Lin
Min Lin

Reputation: 3197

Of course you can do it.

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

But only diagonal of

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

is needed.

So replace

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

with:

sum(  [a(:),b(:)]'  .*  (ver*[a(:),b(:)]') , 1)'

Upvotes: 1

Related Questions