【问题标题】:matching two matrices in matlab在matlab中匹配两个矩阵
【发布时间】:2023-03-30 17:11:01
【问题描述】:

假设我有两个矩阵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 中的行是什么

例如:矩阵 p 中的值 3,位于第 6 行第 1 列

然后将其排序后位于第 2 行第 1 列的矩阵 y

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

【问题讨论】:

  • 如果列中有重复值会怎样?你是如何对列进行排序的?

标签: matlab matrix


【解决方案1】:

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

[y ind] = sort(p);

您想要的结果(每个值的原始行)在矩阵 ind 中。

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

      【解决方案3】:

      好的,我明白你想要什么。

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

      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
      

      瞧!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-12
        相关资源
        最近更新 更多