Average of group of non zero elements in an array

1 visualizzazione (ultimi 30 giorni)
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.

Risposta accettata

Stephen23
Stephen23 il 27 Feb 2018
Modificato: Stephen23 il 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

Più risposte (1)

Prasanna Venkatesh
Prasanna Venkatesh il 27 Feb 2018
Thank you! that works perfectly.
  1 Commento
Stephen23
Stephen23 il 27 Feb 2018
Modificato: Stephen23 il 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.

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by