Average of group of non zero elements in an array
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
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
0 Comments
More Answers (1)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!