function E = rmse(F,A,varargin)
%MATLAB Code Generation Library Function

%RMSE Root-mean-square error.
%#codegen

% Copyright 2022 The MathWorks, Inc.

coder.internal.prefer_const(varargin);

[D,isDimSet,dim,omitnan,~,isWeighted,w] = ...
    parseErrorMetricsInput(false,F,A,varargin{:});

if isreal(D)
    X = D.^2;
else
    % We return a real result
    X = real(D).^2 + imag(D).^2;
end

if omitnan
    nanflag = 'omitnan';
else
    nanflag = 'includenan';
end

% Compute RMSE
if isWeighted
    Y = w.*X;
    if isDimSet
        % Branching due to the edge case where X is empty.
        E = sqrt(sum(Y,dim,nanflag) ./ sum(w,dim,nanflag));
    else
        E = sqrt(sum(Y,nanflag) ./ sum(w,nanflag));
    end
else
    Y = X;
    if isDimSet
        % Branching due to the edge case where X is empty.
        E = sqrt(mean(Y,dim,nanflag));
    else
        E = sqrt(mean(Y,nanflag));
    end
end

if omitnan && anynan(Y)
    % Check if new NaNs were created during computation,
    % e.g. Inf - Inf, 0 * Inf, etc.
    % Do not omit NaNs caused by this computation (not missing data).
    if isWeighted
        isNaNMade = isnan(Y) & ~isnan(w) & ~isnan(F) & ~isnan(A);
    else
        isNaNMade = isnan(Y) & ~isnan(F) & ~isnan(A);
    end
    E(any(isNaNMade,dim)) = coder.internal.nan;
end
end