function [bus,line,nPQ,nPV,nodenum] = sortbus(bus,line)
% returns the bus data matrix in the required sequence of bus type
% [BUS,LINE,NPQ,NPV,NODENUM]= sortbus(BUS,LINE) returns the standard bus
% data and line data with preparation;
% nPQ and nPV are the counts of the PQ & PV bus numbers;
% nodenum is the matrix to record which bus number to be changed.
% Author(s):Long
% $Date:2010/06/27 13:31$
% Bus data
% Bus Bus Voltage Angle ---Load--- ------Generator---- Injected
% No Type Mag. Degree MW Mvar MW Mvar Qmin Qmax Mvar
bus = [1 2 1.06 0 0 0 0 0 0 0 0
2 3 1 0 -0.2 -0.1 0.4 0.3 0 0 0
3 2 1 0 -0.45 -0.15 0 0 0 0 0
4 2 1 0 -0.4 -0.05 0 0 0 0 0
5 2 1 0 -0.6 -0.1 0 0 0 0 0 ];
% Line data
% Bus Bus R X 1/2 B [Link] Setting
% nl nr p.u. p.u. p.u. p.u.
line = [1 2 0.02 0.06 0.03 1
1 3 0.08 0.24 0.025 1
2 3 0.06 0.25 0.02 1
2 4 0.06 0.18 0.02 1
2 5 0.04 0.12 0.015 1
3 4 0.01 0.03 0.01 1
4 5 0.08 0.24 0.025 1];
[nb,mb] = size(bus);
[n1,m1] = size(line);
n = nb;
nSB = 1;
nPV = 0;
nPQ = 0;
for i = 1:n
type=bus(i,2);
if type==3 % Slack Bus
SB(nSB,:) = bus(i,:);
elseif type==2 % PV bus
nPV = nPV+1;
PV(nPV,:) = bus(i,:);
else nPQ = nPQ+1; % PQ bus
PQ(nPQ,:) = bus(i,:);
end
end
if nPV == 0
bus = [PQ;SB] % sort bus numbers
nodenum = [[1:nb]' bus(:,1)];
elseif nPV ~= 0
bus = [PQ;PV;SB] % sort bus numbers
nodenum = [[1:nb]' bus(:,1)];
end
% change bus numbers in line matrix
for i = 1:n1
for j = 1:2
for k = 1:nb
if line(i,j)==nodenum(k,2);
line(i,j) = nodenum(k,1);
break
end
end
end
end
bus(:,1) = [1:nb]'; % update bus numbers