寻找满足特定条件的元素

时间:2015-05-17 09:07:53

标签: matlab find

我有一个矩阵A,我想找到第一行的第二行中有1的元素。即跟随矩阵

 A=
 2     5     6     1
 1     0     0     1 

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

1 个答案:

答案 0 :(得分: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

对于Cell Array

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