Vectorization of nested for loops

hi, This is Pinaki. I am having a problem regarding the code execution time. The following code is taking almost 54 % of total run time to execute. Pls help me to victorize the following codes.
for m = 1:nbus
for n = 1:nbus
if m ~= n
Sij(m,n) = Vm(m)*conj(Iij(m,n))*BMVa;
end
end
end
Thanks, Pinaki

 Accepted Answer

Assuming Vm is a column vector (if not, change it so it is) and BmVa is a scalar:
assert(iscolumn(Vm), 'Vm must be a column vector');
assert(isscalar(BMVa), 'BMVa must be scalar');
Sijall = bsxfun(@times, Vm, conj(Iij) * BMVa);
This will calculate values for Sij even on the diagonal. If Sij is just zeros and you want that diagonal to stay 0:
Sij = Sijall .* ~eye(size(Sijall))
If it has values on the diagonal that you want to preserve:
Sij = Sij .* eye(size(Sij)) + Sijall .* ~eye(size(Sij))

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!