Find Matrix Elements That Meet a Condition
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Stephan Raczak
am 12 Sep. 2016
Kommentiert: Stephan Raczak
am 12 Sep. 2016
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.
0 Kommentare
Akzeptierte Antwort
KSSV
am 12 Sep. 2016
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
Weitere Antworten (1)
Stephen23
am 12 Sep. 2016
Bearbeitet: Stephen23
am 12 Sep. 2016
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.:
0 Kommentare
Siehe auch
Kategorien
Mehr zu NaNs finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!