I have an array that has the following pattern, lets call it A
A=[NaN NaN...NaN 0 1.445 4.223 5.353 1.3534 NaN NaN...NaN 2.45 1.54 0.98 ....NaN....] What I want to do is to calculate the sum of each group of numbers that appear after the each group of NaNs, for example sum(0 1.445 4.223 5.353 1.3534) = B(1), sum(2.45 1.54 0.98)= B(2), and so on.
Can you please guide me through an efficient way to do this?
It is not trivial actually. Look at the following and let me know if there is anything unclear. Also, I let you check that it manages well limit cases, and update it otherwise.
isnanId = isnan(A) ; groupId = [1, isnanId(1:end-1)] ; groupId = cumsum(groupId(~isnanId)) ; A = A(~isnanId) ; B = accumarray(groupId(:), A(:)) ;
Running this code produces:
>> B B = 12.3744 4.9700
which is the group-sum that you are looking for.