在matlab中匹配两个矩阵

时间:2013-11-22 18:35:24

标签: matlab matrix

假设我有两个矩阵p

p =
 1     3     6     7     3     6
 8     5    10    10    10     4
 5     4     8     9     1     7
 5     5     5     3     8     9
 9     3     5     4     3     1
 3     3     9    10     4     1

然后将矩阵p的列排序为升序

y =  
 1     3     5     3     1     1
 3     3     5     4     3     1
 5     3     6     7     3     4
 5     4     8     9     4     6
 8     5     9    10     8     7
 9     5    10    10    10     9

我想知道,给定y的值,p中的行是什么

ex:位于第6行第1列的矩阵p中的值3

然后在排序后将其放在第2行第1列的矩阵y

所以我想在矩阵y中排序之后的最后值,它最初位于矩阵p

3 个答案:

答案 0 :(得分:1)

Matlab sort命令返回第二个值,该值可用于索引原始数组或矩阵。来自sort文档:

[Y,I] = sort(X,DIM,MODE) also returns an index matrix I.
If X is a vector, then Y = X(I).  
If X is an m-by-n matrix and DIM=1, then
    for j = 1:n, Y(:,j) = X(I(:,j),j); end

答案 1 :(得分:1)

只需使用sort的第二个输出:

[y ind] = sort(p);

您想要的结果(每个值的原始行)位于矩阵ind

答案 2 :(得分:0)

好的,我完全理解你想要的东西。

我会给你我现在写的代码,它不是最佳的,但你可以优化它,或者我可以和你合作以获得更好的代码..

P和y具有相同的大小。

    [n,m]=size(p);

    for L=1:m
    i=1;
    temp=y(i,L);
    while(i<=n)
    if(temp==y(i,L))
    % So it is present in case i of p
    disp(['It is present in line' num2str(i) ' of p']);

    end
    i=i+1;
    end
    end

瞧!!