Please help regarding the vectorization of the code. Thanks

P = zeros(nbus,1);
Q = zeros(nbus,1);
for i=1:nbus
for j=1:nbus
P(i)= P(i)+V(i)*V(j)*(G(i,j)*cos(del(i)-del(j))+B(i,j)*sin(del(i)-del(j)));
Q(i)= Q(i)+V(i)*V(j)*(G(i,j)*sin(del(i)-del(j))-B(i,j)*cos(del(i)-del(j)));
end
end

1 Comment

What are V, G, B, and del?
Instead of giving us incomplete code, please give us a complete working example that we can try.

Answers (1)

Learn to use bsxfun and outer product ( see first example of mtimes):
%assuming V and del are row vector
assert(isrow(V), 'V must be a row vector');
assert(isrow(del), 'del must be a row vector');
deldiff = bsxfun(@minus, del', del);
P = sum(V'*V .* (G.*cos(deldiff) + B.*sin(deldiff)), 2)
Q = sum(V'*V .* (G.*sin(deldiff) - B.*cos(deldiff)), 2)

This question is closed.

Asked:

on 5 Jan 2016

Closed:

on 20 Aug 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!