Ignoring NaN values in a function

I am trying to create a function to calculate an index consisting of 6 variables (x1,x2,x3,x4,x5,x6).
Any number of the following variables (x2,x3,x4,x5,x6) may have a value of NaN.
Example 1:
If x2 = NaN
I want exclude d2 from the index equation and divde it by squareroot of 5 insted of squareroot 6.
Example 2:
If x2 = NaN and x3=NaN
I want exclude d2 and d3 from the index equation and divde it by squareroot of 4 insted of squareroot 6.
In the below code I could set if isnan (x2) then d2=0 but I am not sure how to set the denominator = sqrt (n number of d).
How to code the function efficiently ?
function index = anna (x1,x2,x3,x4,x5,x6)
offset = 1;
d1 = (((1-x1).^2) * 0.5);
d2 = ((1-x2).^2);
d3 = ((1-x3).^2);
d4 = ((1-x4).^2);
d5 = ((1-x5).^2);
d6 = ((1-x6).^2);
index = (offset - ( sqrt ( (d1) + (((d2) + (d3) + (d4) + (d5) + (d6))* 0.5)))/ sqrt(6));
% "sqrt(6)" is n number of d

1 comentario

I have tried the following code but I am still getting NaN values and exact same answers as the above code.
Example Answers:
Index(n)=0.4756, 0.3644, NaN, 0.3443,...........
n=190
I am not sure where I am going wrong.
function index = anna(x1,x2,x3,x4,x5,x6)
offset = 1;
% If x2,x3,x4,x5,x6 is NaN then d2,d3,d4,d5,d6 should be 0 else d2 =
% ((1-x2).^2)..........
if isnan(x2), d2 = (0);
else ,d2 = ((1-x2).^2);
end
if isnan(x3), d3 = (0);
else ,d3 = ((1-x3).^2);
end
if isnan(x4), d4 = (0);
else ,d4 = ((1-x4).^2);
end
if isnan(x5), d5 = (0);
else ,d5 = ((1-x5).^2);
end
if isnan(x6), d6 = (0);
else ,d6 = ((1-x6).^2);
end
d1 = (((1-x1).^2) * 0.5);
dn = 6; %Total number of dimensions
%For every x2,3,4,5,6 that is NaN substract 1 from total dimensions
if isnan(x6)
(dn(-1));
end
if isnan(x6)
(dn(-1));
end
if isnan(x6)
(dn(-1));
end
if isnan(x5)
(dn(-1));
end
if isnan(x6)
(dn(-1));
end
index = (offset - ( sqrt ( (d1) + (((d2) + (d3) + (d4) + (d5) + (d6))* 0.5)))/ sqrt(dn));

Iniciar sesión para comentar.

Respuestas (1)

Matt J
Matt J el 9 de Mzo. de 2019
Editada: Matt J el 9 de Mzo. de 2019
function index = anna(x) %x is vector of arbitrary length
offset=1;
d=0.5*(1-x).^2;
index=offset-sqrt(mean(d,'omitnan'));
end

2 comentarios

Syed Anas Ahmed
Syed Anas Ahmed el 9 de Mzo. de 2019
Thanks for the answer but each x variable has 190 diffrent values and some of them are NaN.
Matt J
Matt J el 9 de Mzo. de 2019
Editada: Matt J el 9 de Mzo. de 2019
Then you should pass in x as a 6x190 matrix. Code remains the same.

Iniciar sesión para comentar.

Categorías

Productos

Versión

R2018b

Preguntada:

el 9 de Mzo. de 2019

Editada:

el 9 de Mzo. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by