查找满足特定条件的元素
Finding elements who meet a specific condition
我有一个矩阵 A,我想找到第一行中第二行有 1 的元素。即对于以下矩阵
A=
2 5 6 1
1 0 0 1
我希望在不使用循环的情况下将输出作为 hits = [2 1]。然后找到答案中的最大项目。即 (2>1) 所以我的最终答案是 2。响应可能是使用 arrayfun 但我遇到问题并在使用它时出错。正确的语法是什么?
谢谢
试试这个:
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
我有一个矩阵 A,我想找到第一行中第二行有 1 的元素。即对于以下矩阵
A=
2 5 6 1
1 0 0 1
我希望在不使用循环的情况下将输出作为 hits = [2 1]。然后找到答案中的最大项目。即 (2>1) 所以我的最终答案是 2。响应可能是使用 arrayfun 但我遇到问题并在使用它时出错。正确的语法是什么? 谢谢
试试这个:
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