want to calculate the sum of the numbers appear in an array that is mix of NaNs and numbers
Show older comments
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?
Accepted Answer
More Answers (1)
Azzi Abdelmalek
on 1 May 2013
A=[NaN NaN NaN 1 2 3 NaN NaN NaN 4 5 6 10 NaN NaN 2 NaN NaN 1 2 0 4]
idx=find(~isnan(A))
id=[1 diff(idx)]
ii=[1 find(id>1)]
for k=1:numel(ii)-1
s(k)=sum(A(idx(ii(k)):idx(ii(k+1)-1)))
end
s(k+1)=sum(A(idx(ii(k+1)):idx(end)))
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!