Ignoring NaN values in a function
Show older comments
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 Comment
Syed Anas Ahmed
on 9 Mar 2019
Answers (1)
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
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!