简体   繁体   English

如何找到小于阈值的矩阵每一行中的元素数

[英]how to find the number of elements in each row of a matrix that is smaller than a threshhold

The question is just as the title. 问题与标题一样。 I can do it by using loops. 我可以使用循环来做到这一点。 However, I wonder is there a better way to achieve this without a loop. 但是,我想知道有没有更好的方法来实现此目的而无需循环。 Thanks. 谢谢。 In case I did not make my question clear, the following code shows what I want using loops. 如果我的问题不清楚,下面的代码显示了我想要使用循环的内容。 By the way, the data in each row is sorted from the smallest to the largest, from the left to the right. 顺便说一句,每行中的数据从最小到最大,从左到右排序。

Mat = rand(20);
Mat = sort(Mat,2);
Mat(:,1) = 0; % in case these is no element smaller than the threshold
result = zeros(20,1);
threshold = 0.2;
for i = 1:20
    result(i) = length(find(Mat(i,:) < threshold));
end

您可以使用条件构造一个logical矩阵,然后sum每一行sum以找到符合条件的项目数

result = sum(Mat < threshold, 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM