Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab sum function of NAN values

Tags:

sum

matlab

I have a matrix with potential NAN values. For example, A=[1,nan,1;nan,nan,nan]. I would like to have a summation by rows that looks like [2;nan], but could not find an easy and clean way of doing this. Any suggestions?

I am aware of the use of 'omitnan' option but it would only give me [2;0].

like image 801
Kryvtsov Avatar asked Sep 15 '25 08:09

Kryvtsov


1 Answers

I know this might seem like over-engineering the solution, but here is a code excerpt that will work. You calculate the absolute sums of each of the rows using the 'omitnan' flag and then cross reference those rows where all elements are NaNs in the nan_check variable. Multiplying these together gives you the resultant matrix where all rows are summed up, and any rows that had all NaNs show up as NaN.

sumMat = sum(A,2,'omitnan')
nan_check = double(~prod(isnan(A),2))
nan_check(nan_check==0) = NaN
sumMat.*nan_check
like image 162
A-T Avatar answered Sep 18 '25 10:09

A-T