Average of group of non zero elements in an array

1 view (last 30 days)
Hello, I have an array such as
A=[ 0 0 0 0 4 3 5 6 7 0 0 0 0 2 3 4 5 0 0 0] for example.
I want to display the average of all the groups of non zero elements of this array individually. So the above output should give me the average of [4 3 5 6 7] and [ 2 3 4 5] separately. I need this to apply to a problem I have where I have a signal that has non zero values at different intervals and I am trying to find the average values of all such non zero durations individually.
Any help is appreciated.
Thanks.

Accepted Answer

Stephen23
Stephen23 on 27 Feb 2018
Edited: Stephen23 on 27 Feb 2018
>> A = [0,0,0,0,4,3,5,6,7,0,0,0,0,2,3,4,5,0,0,0];
>> D = diff([true;A(:)==0;true]);
>> idb = find(D<0);
>> ide = find(D>0)-1;
>> C = arrayfun(@(b,e)A(b:e),idb,ide,'uni',0);
>> C{:}
ans =
4 3 5 6 7
ans =
2 3 4 5
Or to get the means:
>> arrayfun(@(b,e)mean(A(b:e)),idb,ide)
ans =
5.0000
3.5000

More Answers (1)

Prasanna Venkatesh
Prasanna Venkatesh on 27 Feb 2018
Thank you! that works perfectly.
  1 Comment
Stephen23
Stephen23 on 27 Feb 2018
Edited: Stephen23 on 27 Feb 2018
@Prasanna Venkatesh: thank you. Remember to accept the answer that helps you most: this gives us reputation points, and shows that your question has been resolved.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!