找到矩阵

时间:2015-05-27 00:49:10

标签: matlab function for-loop matrix indexing

我试图在矩阵中找到一个关键点。 index(i,j)处的值应大于或等于其行中的所有元素,并且小于或等于其列中的所有元素。

这是我所拥有的(它关闭但我很接近):

function C = critical(A)
[nrow ncol] = size(A);
C = [];
for i = 1:nrow
    for j = 1:ncol
        if (A(i,j) >= A(i,1:end)) && (A(i,j) <= A(1:end,j))
            C = [C ; A(i,j)]
        end
    end
end

3 个答案:

答案 0 :(得分:3)

您可以使用逻辑索引。

minI = min(A,[],1);
maxI = max(A,[],2);
[row,col] = find(((A.'==maxI.').' & A==minI) ==1)

详细信息

请记住,Matlab是专栏专业。因此,我们转置A和maxI。

A = [

   3   4   1   1   2
   2   4   2   1   4
   4   3   2   1   2
   3   3   1   1   1
   2   3   0   2   1];

A.'==maxI.'
ans =

   0   0   1   1   0
   1   1   0   1   1
   0   0   0   0   0
   0   0   0   0   0
   0   1   0   0   0

然后做最小的

A==minI
ans =

   0   0   0   1   0
   1   0   0   1   0
   0   1   0   1   0
   0   1   0   1   1
   1   1   1   0   1    

然后乘以两个

((A.'==maxI.').' & A==minI)
ans =

   0   0   0   0   0
   0   0   0   0   0
   0   0   0   0   0
   0   1   0   0   0
   0   1   0   0   0

然后找到行和列

[row,col] = find(((A.'==maxI.').' & A==minI) ==1)

row =

   4
   5

col =

   2
   2

答案 1 :(得分:2)

使用bsxfun

尝试此向量化解决方案
function [ r,c,criP ] = critical( A )

    %// finding the min and max values of each col & row resptly
    minI = min(A,[],1);
    maxI = max(A,[],2);

    %// matching all the values of min & max for each col and row resptly 
    %// getting the indexes of the elements satisfying both the conditions
    idx = find(bsxfun(@eq,A,maxI) & bsxfun(@eq,A,minI));

    %// getting the corresponding values from the indexes
    criP = A(idx);

    %// Also getting corresponding row and col sub
    [r,c] = ind2sub(size(A),idx);
end

示例运行

rc应该是一个等长的向量,表示每个临界点的行和列子。虽然val是一个相同长度的向量,给出了临界点本身的值

>> A

A =

 3     4     1     1     2
 2     4     2     1     4
 4     3     2     1     2
 3     3     1     1     1
 2     3     0     2     1


>> [r,c,val] = critical(A)

r =

 4
 5

c =

 2
 2

val =

 3
 3

答案 2 :(得分:2)

我认为intersect有一种更简单的方式:

>> [~, row, col] = intersect(max(A,[],2), min(A));
row =

 4


col =

 2

更新:

使用intersect,如果您有多个关键点,它只会给您第一个关键点。拥有所有的指标,还有另一种简单的方法:

>> B

B =

 3     4     1     4     2     5
 2     5     2     4     4     4
 4     4     2     4     2     4
 3     4     1     4     1     4
 2     5     4     4     4     5

>> row = find(ismember(max(B,[],2),min(B)))

row =

 3
 4

>> col = find(ismember(min(B),max(B,[],2)))

col =

 2     4     6

请注意,现在一组关键点应该是rowcol的组合,这意味着您在此示例中总共有6个关键点:(3,2),(4,2),(3,4),(4,4),(3,6),(4,6)

Here您可以找到如何导出此类组合。