Is there a way to use the RMS function with two options, namely 'omitnan' and an option for the dimension?

5 views (last 30 days)
Take the following matrix as example.
A=repmat([NaN 1 2 3],3,1);
rms(A)
ans =
NaN 1 2 3
rms(A,2)
ans =
NaN
NaN
NaN
There is an 'omitnan' option for rms. E.g.
rms(A','omitnan') % A' is the flipped matrix
ans =
2.1602 2.1602 2.1602
But I can not do both options/inputs at the same time, i.e.
rms(A,2,'omitnan')
%or
rms(A,'omitnan',2)
Both throw the error:
Error using rms
Too many input arguments.
Now, of course I could use a workaround like this:
my_rms=rms(A','omitnan')'; % A' is the flipped matrix;
% note that the outcome of rms() is also flipped
But that seems ugly and also confusing (for my future self) to me. Another workaround (even uglier) would be to for-loop over every single row in A with
for i = 1:3
my_rms(i)=rms(A(i,:),'omitnan');
end
I'm aware that I'm kind of answering my own question by giving work arounds, but as I said, they do not seem nice and clean to me, so I hope someone might have a better idea.

Accepted Answer

Jan
Jan on 24 Apr 2019
Edited: Jan on 24 Apr 2019
There is no documented 'omitnan' argument for rms in current Matlab versions, see: https://www.mathworks.com/help/signal/ref/rms.html (link). I get:
A=repmat([NaN 1 2 3],3,1
rms(A, 'omitnan')
>> [NaN, 1, 2, 3]
But I observe this:
rms(A')
[NaN, 1, 2, 3]
rms(A', 'omitnan')
[2.1602, 2.1602, 2.1602]
This happens, because the dim argument is forwarded to mean without a check inside rms.m:
y = sqrt(mean(x .* x), dim);
If you want the 'omitnan' and the specified dimension, simply use an expanded rms version:
function y = rms2(x, varargin)
if isreal(x)
y = sqrt(mean(x .* x, varargin{:}));
else
absx = abs(x);
y = sqrt(mean(absx .* absx, varargin{:}));
end
end
Add documentation, tests of inputs and number of inputs in addition, as well as the more efficient method to get the absolute value for imaginary input.
If you want to, send an enhancement request to MathWorks, to catch the 'omitnan' flag explicitly.
  2 Comments
JD4
JD4 on 24 Apr 2019
Hi Jan,
I know it is not in the documentation.
Of course,
rms(A,'omitnan')
does yield the same as
rms(A)
but if you flip A, i.e.
B=A'
ans =
NaN NaN NaN
1 1 1
2 2 2
3 3 3
and then try
rms(B)
you get
ans =
NaN NaN NaN
but with
rms(B,'omitnan')
you get
ans =
2.1602 2.1602 2.1602

Sign in to comment.

More Answers (1)

Matt J
Matt J on 24 Apr 2019
Edited: Matt J on 24 Apr 2019
Here's a better workaround. In this implementation, all the same input syntax options as for mean() are available.
function out=rms(A,varargin)
out=sqrt(mean(A.^2,varargin{:}));
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!