1function [A,B,Q,Z] = qzswitch(i,A,B,Q,Z)
2%function [A,B,Q,Z] = qzswitch(i,A,B,Q,Z)
3%
4% Takes U.T. matrices A, B, orthonormal matrices Q,Z, interchanges
5% diagonal elements i and i+1 of both A and B, while maintaining
6% Q'AZ' and Q'BZ' unchanged.  If diagonal elements of A and B
7% are zero at matching positions, the returned A will have zeros at both
8% positions on the diagonal.  This is natural behavior if this routine is used
9% to drive all zeros on the diagonal of A to the lower right, but in this case
10% the qz transformation is not unique and it is not possible simply to switch
11% the positions of the diagonal elements of both A and B.
12
13% Original file downloaded from:
14% http://sims.princeton.edu/yftp/gensys/mfiles/qzswitch.m
15
16% Copyright (C) 1993-2007 Christopher Sims
17% Copyright (C) 2008-2011 Dynare Team
18%
19% This file is part of Dynare.
20%
21% Dynare is free software: you can redistribute it and/or modify
22% it under the terms of the GNU General Public License as published by
23% the Free Software Foundation, either version 3 of the License, or
24% (at your option) any later version.
25%
26% Dynare is distributed in the hope that it will be useful,
27% but WITHOUT ANY WARRANTY; without even the implied warranty of
28% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29% GNU General Public License for more details.
30%
31% You should have received a copy of the GNU General Public License
32% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
33
34realsmall=sqrt(eps)*10;
35%realsmall=1e-3;
36a = A(i,i); d = B(i,i); b = A(i,i+1); e = B(i,i+1);
37c = A(i+1,i+1); f = B(i+1,i+1);
38% A(i:i+1,i:i+1)=[a b; 0 c];
39% B(i:i+1,i:i+1)=[d e; 0 f];
40if (abs(c)<realsmall && abs(f)<realsmall)
41    if abs(a)<realsmall
42        % l.r. coincident 0's with u.l. of A=0; do nothing
43        return
44    else
45        % l.r. coincident zeros; put 0 in u.l. of a
46        wz=[b; -a];
47        wz=wz/sqrt(wz'*wz);
48        wz=[wz [wz(2)';-wz(1)'] ];
49        xy=eye(2);
50    end
51elseif (abs(a)<realsmall && abs(d)<realsmall)
52    if abs(c)<realsmall
53        % u.l. coincident zeros with l.r. of A=0; do nothing
54        return
55    else
56        % u.l. coincident zeros; put 0 in l.r. of A
57        wz=eye(2);
58        xy=[c -b];
59        xy=xy/sqrt(xy*xy');
60        xy=[[xy(2)' -xy(1)'];xy];
61    end
62else
63    % usual case
64    wz = [c*e-f*b, (c*d-f*a)'];
65    xy = [(b*d-e*a)', (c*d-f*a)'];
66    n = sqrt(wz*wz');
67    m = sqrt(xy*xy');
68    if m<eps*100
69        % all elements of A and B proportional
70        return
71    end
72    wz = n\wz;
73    xy = m\xy;
74    wz = [wz; -wz(2)', wz(1)'];
75    xy = [xy;-xy(2)', xy(1)'];
76end
77A(i:i+1,:) = xy*A(i:i+1,:);
78B(i:i+1,:) = xy*B(i:i+1,:);
79A(:,i:i+1) = A(:,i:i+1)*wz;
80B(:,i:i+1) = B(:,i:i+1)*wz;
81Z(:,i:i+1) = Z(:,i:i+1)*wz;
82Q(i:i+1,:) = xy*Q(i:i+1,:);