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

%   Copyright 2003-2023 The MathWorks, Inc.

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

% Calculate the S-parameters: S = (Kinv+Y*K)\(Kinv-Y*K)
% see Young, Digital Signal Integrity, Exercise 5 on p. 167
[K,Kinv] = referenceImpedanceArrays(y_params,z0);
yK = pagemtimes(y_params,K);
s_params = pagemldivide(Kinv+yK,Kinv-yK);
