Find Matrix Elements That Meet a Condition
15 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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
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.:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 NaNs 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!