How can I vectorize these loops in Matlab?

You can post your problem related to MATLAB Projects here. We will try our best to help you out.
Post Reply
Charles
Posts: 20
Joined: Sat Feb 18, 2017 7:12 am

How can I vectorize these loops in Matlab?

Post by Charles » Mon Mar 06, 2017 12:26 pm

Code: Select all

function[Y] = busadmittance(z)
ne = z(:,1); nt = z(:,2); r = z(:,3); x = z(:,4); lines = length(ne);   
buses = max(max(ne), max(nt));                         
Z = r + 1j*x;                            
y = ones(length(Z),1)./Z;                            
Y = zeros(buses,buses);       
How can I vectorize below 'for' loops, that follows the above code?

Code: Select all

for k = 1:buses                         
    for l = 1:lines
        if ne(l) == k || nt(l) == k
        Y(k,k) = Y(k,k)+ y(l);
        end
    end
end

for k = 1:lines                          
    if ne(k)>0 && nt(k) > 0 
        Y(ne(k),nt(k)) = -y(k);
        Y(nt(k),ne(k)) = -y(k);
    end
end
are there any additional code enhancements apart from preallocation and vectorization, that can greatly affect the performance? (forget gpu, cluster)

Post Reply