function y_params = s2y(s_params,z0)
%S2Y Convert S-parameters to Y-parameters
%   Y_PARAMS = S2Y(S_PARAMS, Z0) converts the scattering parameters
%   S_PARAMS into the admittance parameters Y_PARAMS.
%
%   S_PARAMS is a complex NxNxM array of M N-port S-parameters. Z0 is the
%   reference impedance, the default is 50 ohms. The output Y_PARAMS is a
%   complex NxNxM array of M N-port Y-parameters.
%
%   Z0 is specified as one of the following:
%   - Scalar used for all ports and frequencies
%   - Vector of length size(S_PARAMS,1), for per-port impedances
%   - Vector of length size(S_PARAMS,3), for per-frequency impedances
%
%   If size(S_PARAMS,1) == size(S_PARAMS,3) == numel(Z0), then Z0
%   specifies per-port impedances, unless Z0 is a 3-D array.
%
%   See also Y2S, S2Z, S2H, S2ABCD, Z2Y, H2Y, ABCD2Y

%   Copyright 2003-2023 The MathWorks, Inc.

arguments
    s_params {mustBeNumeric,mustBeNonempty,mustBeNonNan, ...
        rf.internal.mustBeVectorOrNxNxM}
    z0 {mustBeNumeric,mustBeNonempty,mustBeFinite, ...
        rf.internal.mustBeRealValued, ...
        rf.internal.mustBeDataSized(z0,s_params)} = 50
end
if isvector(s_params)
    s_params = reshape(s_params,1,1,[]);
end

% Calculate the Y-parameters:  Y = Kinv*(I-S)*inv(I+S)*Kinv
% see Young, Digital Signal Integrity, Exercise 6 on p. 167
I = eye(size(s_params,1));
[~,Kinv] = referenceImpedanceArrays(s_params,z0);
y_params = ...
    pagemtimes(pagemrdivide(pagemtimes(Kinv,I-s_params),I+s_params),Kinv);
