필터 지우기
필터 지우기

Find Matrix Elements That Meet a Condition

조회 수: 5 (최근 30일)
Stephan Raczak
Stephan Raczak 2016년 9월 12일
댓글: Stephan Raczak 2016년 9월 12일
I have a 1025x36 single matrix A and I like to find specific matrix elements by having the following condition fulfilled:
B = A( A>4 & A<8);
After finding all the values that meet this condition, I would like these values to be averaged columnwise for each of the 36 columns.
Can somebody help how to do this. When I find the values that meet the condition, they all get concatenated vertically and I am unable to calculate the mean for these values per column.

채택된 답변

KSSV
KSSV 2016년 9월 12일
You can pick a particular column and run a loop.
for i = 1:36
C = A(:,i) ;
B = C( C>4 & C<8);
%%Do what you want
end

추가 답변 (1개)

Stephen23
Stephen23 2016년 9월 12일
편집: Stephen23 2016년 9월 12일
Although there are many ways of doing this, here are two robust methods. Note that using a loop might seem attractive to beginners, but is not a very effective use of MATLAB's abilities, and will not scale well to larger array sizes.
Method One: DIY: add zeros in the non-matching locations, and then calculate the mean yourself:
>> A = randi(9,7,10)
A =
8 5 3 3 6 7 5 9 7 9
4 5 7 7 4 3 2 3 5 2
1 8 3 8 9 8 4 7 4 7
3 5 7 4 1 5 6 2 6 3
2 9 7 8 5 1 2 3 6 2
3 6 1 7 4 2 7 1 7 6
4 9 3 1 5 7 3 6 6 5
>> B = A;
>> idx = A>4 & A<8;
>> B(~idx) = 0;
>> sum(B,1) ./ sum(idx,1)
ans =
NaN 5.2500 7.0000 7.0000 5.3333 6.3333 6.0000 6.5000 6.1667 6.0000
Method Two: use nanmean. Add NaN in the non-matching locations, and then use the nanmean function (which ignores the NaNs):
>> B = A;
>> B(~(A>4 & A<8)) = NaN;
>> nanmean(B,1)
ans =
NaN 5.2500 7.0000 7.0000 5.3333 6.3333 6.0000 6.5000 6.1667 6.0000
If your MATLAB version does not have nanmean, then you can find some versions on File Exchange, e.g.:

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by