MATLAB: Sum two variables ignoring NaN MATLAB I have table T Var1 Var2--------------1 NaNNaN 2 I want to add var1 and var2 ignoring NaN: sum ---12 Best Answer Try this:var1 = [1;2;3;nan];var2 = [4;nan;6; 15];t = table(var1, var2)% Initialize with var1theSum = t.var1;% If any are nan, replace with value from var2.badRows = isnan(theSum)theSum(badRows) = t.var2(badRows)% If both are not nan, make it the sumgoodRows1 = ~isnan(t.var1)goodRows2 = ~isnan(t.var2)goodRows = goodRows1 & goodRows2;theSum(goodRows) = t.var1(goodRows) + t.var2(goodRows)You get:t = 4×2 table var1 var2 ____ ____ 1 4 2 NaN 3 6 NaN 15 theSum = 5 2 9 15If one is nan, you get the other one which is not a nan.If both are nans, you get a nan.If both are not nan, you get the sum. Related SolutionsMATLAB: How to select or group sections of an array without using indexing >> A = [NaN, NaN, NaN, NaN, 2, 3, 6, 7, NaN, NaN, NaN, NaN, NaN, 4, 6, 8, 8, NaN, NaN, NaN, NaN];>> X = diff([true,isnan(A),true]);>> B = find(X<0);>> E = find(X>0)-1;>> F = @(b,e) A(b:e);>> C = arrayfun(F,B,E,'uni',0);>> C{1}ans = 2 3 6 7>> C{2}ans = 4 6 8 8 MATLAB: How to vertically concatenate two tables with different sizes outerjoin(A,B,'MergeKeys', true)It took me a few minutes to find the right command. Related QuestionHow to sort rows of matrix according ot its amount of NanHow do we eliminated (empty or zeros) Columns or Rows from tables in MatlabReplacing elements in a tableHow to replace values above a given percentile by nansExisting table, populate a column with string (receiving errors)
Best Answer