Average of group of non zero elements in an array

조회 수: 1 (최근 30일)
Prasanna Venkatesh
Prasanna Venkatesh 2018년 2월 27일
편집: Stephen23 2018년 2월 27일
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.

채택된 답변

Stephen23
Stephen23 2018년 2월 27일
편집: Stephen23 2018년 2월 27일
>> 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

추가 답변 (1개)

Prasanna Venkatesh
Prasanna Venkatesh 2018년 2월 27일
Thank you! that works perfectly.
  댓글 수: 1
Stephen23
Stephen23 2018년 2월 27일
편집: Stephen23 2018년 2월 27일
@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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by