Hi Balsip
1.
while
A=[NaN NaN -12 NaN NaN NaN NaN -1 -5 -8 NaN NaN NaN NaN -20 NaN NaN -3];
mean(A)
median(A)
nanmean(A)
nanmedian(A)
=
NaN
=
NaN
=
-8.1667
=
-6.5000
as expected, mean and median ignore NaN
mean([-12 -1 -5 -8 -20 -3])
=
-8.1667
median([-12 -1 -5 -8 -20 -3])
=
-6.5000
.
2.
however when 1/0
A=[NaN NaN -12 NaN NaN NaN NaN -1 -5 -8 NaN NaN 1/0 NaN -20 NaN NaN -3];
mean(A)
median(A)
nanmean(A)
nanmedian(A)
ans =
NaN
ans =
NaN
ans =
Inf
ans =
-5
or Inf are part of vector A,
A=[NaN NaN -12 NaN NaN NaN NaN -1 -5 -8 NaN NaN Inf NaN -20 NaN NaN -3];
mean(A)
median(A)
nanmean(A)
nanmedian(A)
ans =
NaN
ans =
NaN
ans =
Inf
ans =
-5
.
3.
nanmean takes into account Inf values but nanmedian doesn't. This is because
and/or
have one or more null values, introducing Inf s elements in A.
.
4.
to avoid this, either directly correct Infs to NaNs
or on Y1 and X2, remove their nulls
tol=.000001;
Y1(find(Y1==0))=tol;
X2(find(X2==0))=tol;
Let tol be a really small, small enough so it can be ignored.
5.
It could also be that Y2 and/or X1 elements take Inf values but I assumed from the question that such is not the case, so only one or more elements of Y1 and X2 are null.
6.
Balsip, please note that although
and
for i=1:length(X1)
A(i)=(X1(i)./Y1(i))./(X2(i)./Y2(i));
end
are mathematically the same, the time consumption of the compact expression is 1 order of magnitude better than the for loop
L=1e7;
X1=randi([1 1e4],1,L);Y1=randi([1 1e4],1,L);
X2=randi([1 1e4],1,L);Y2=randi([1 1e4],1,L);
tic
A=(X1./Y1)./(X2./Y2);
toc
Elapsed time is 0.038204 seconds.
>> tic
for i=1:length(X1)
A(i)=(X1(i)./Y1(i))./(X2(i)./Y2(i));
end
toc
Elapsed time is 0.236449 seconds.
.
the operator ./ is optimised against the for loop you attempted to use a possible solution.
.
Balsip
if you find this answer useful would you please be so kind to consider marking my answer as Accepted Answer?
To any other reader, if you find this answer useful please consider clicking on the thumbs-up vote link
thanks in advance
John BG