【问题标题】:Finding elements who meet a specific condition查找满足特定条件的元素
【发布时间】:2015-05-17 09:07:53
【问题描述】:

我有一个矩阵 A,我想找到第一行中第二行有 1 的元素。即对于以下矩阵

 A=
 2     5     6     1
 1     0     0     1 

我希望输出为 hits = [2 1] 而不使用循环。然后找到答案中的最大项目。即(2>1)所以我的最终答案是2。响应可能是使用arrayfun,但我遇到问题并且使用它时出错。什么是正确的语法? 谢谢

【问题讨论】:

    标签: matlab find


    【解决方案1】:

    试试这个:

    out = max(A(1,A(2,:) == 1))
    

    示例:

    >> A
    
    A =
    
     2     5     6     1
     1     0     0     1
    
    >> out
    
    out =
    
     2
    

    说明:(如果需要)

    %// create a mask of which column you want
    mask = A(2,:) == 1   %// by checking all values of 2nd row with 1
    
    %// get only the values of row one, meeting 'the' condition
    hits = A(1,mask)  
    
    %// Find the maximum from that
    maxHits = max(hits)
    

    对于元胞数组使用cellfun

    A = {[2 5 6 1; 1 0 0 1], [2 3 2 5 4; 1 1 3 1 2]}  %// eg input
    
    A = 
    
    [2x4 double]    [2x5 double]
    
    out = cellfun(@(x) max(x(1,x(2,:) == 1)),A)
    
    out =
    
     2     5
    

    【讨论】:

    • 谢谢,完美的解决方案。现在,如果它在 cellarray 的情况下,例如a{1}={ 2 5 6 1; 1 0 0 1} ; a{2}={ 3 2 4 1; 1 0 0 0}。我们也可以针对这种情况调整解决方案吗? (查找具有相应值的值,然后获取最大元素)
    • @hamideh 确保检查编辑.. 将示例 A 更改为您的实际值并进行测试:)
    • 谢谢,Big Bravo :) 另一个转折点:如果我们想首先检查匹配出现的次数,(单元格 1 中的 2 1 和单元格 2 中的 2 3 5)那么我们可以这样做out = cellfun(@(x) numel(x(1,x(2,:) == 1)),A) ?out = [2 3] 那么只有在出现次数相等的情况下,再次执行函数final_out= cellfun(@(x) max(x(1,x(2,:) == 1)),A),对吧?
    • @hamideh 如果它们不相等怎么办?你只想找到maxhits,前提是它们的出现次数相同?
    • 例如在您的示例中 A = {[2 5 6 1]; [2 3 2 5 4]}, B=[5 6 7] ;然后因为 A{1} 中的命中大于 A{2} [2 1],所以我选择 A{1} 作为获胜单元格。如果可能的话,我会尝试找到一种方法来使用 cellfun 并报告结果..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 2021-05-15
    • 1970-01-01
    • 2013-02-05
    • 2018-07-27
    • 2020-05-20
    • 1970-01-01
    相关资源
    最近更新 更多