【问题标题】:Indexing a matrix using predetermined rule使用预定规则索引矩阵
【发布时间】:2015-06-11 13:51:47
【问题描述】:

我有一个 72x3 double,看起来像这样

1   1   24  
1   1   125  
2   3   17  
6   2   54  
5   1   110  
4   4   55  
6   2   200
1   4   16  
3   3   87  
...  
6   2   63  

我希望能够根据第 1 列和第 2 列中的值的组合从第 3 列中找到一个值。例如,我们将第 1 列中的任何值称为 m,列中的值2 n,以及第 3 列 p 中的相应值。如果 m=2, n=3,这将对应于第 3 行,因此 p 将是 >17。如果 m=5, n=1,这将给我们第 5 行,因此 b 将是 110。请注意,在某些情况下,一组 mn 会给我们两行或更多行。一个例子是 m=1n1=1,它们应该从第一行产生 24125从第二行开始。在这种情况下,输出应该是 [24 125]。同样,m=6n=2 的组合将得到 [54 200 63]m 范围从 1 到 6,n 范围从 1 到 4。mn 的任意组合都会产生不超过 4 个输出。谁能帮我解决这个索引问题?

非常感谢。

亚历克斯

【问题讨论】:

  • 您能否发布预期的输出,只是为了查看输出的呈现方式

标签: matlab indexing


【解决方案1】:

如果您只想要mn 的给定组合的结果,您可以只使用索引:

m = 6;
n = 2;
result = x(x(:,1)==m & x(:,2)==n, 3).';

【讨论】:

  • 哇,这个效率很高。谢谢你,路易斯!
【解决方案2】:

这不会是最快的方法,但对于像我这样的初学者来说是另一种方法:)

in = [1   1   24; 
      1   1   125;
      2   3   17;
      6   2   54;  
      5   1   110;
      4   4   55;
      6   2   200;
      1   4   16;
      3   3   87];
m = input('Enter m ');
n = input('Enter n ');
Idx = all((cat(2,in(:,1) == m, in(:,2) == n)),2); 
out = in(:,3);
out1 = out(Idx);

结果:

Enter m 6
Enter n 2

ans =

    54
   200
----------------

Enter m 2
Enter n 3

ans =

    17

【讨论】:

  • 谢谢你,桑坦!这确实很简单,我可以理解。非常感谢您的帮助!
【解决方案3】:

一种方法假设A 是输入N x 3 数组-

%// Find unique rows using the first two columns of A
[unqA12,~,idx] = unique(A(:,1:2),'rows')

%// Group elements from 3rd column of A based on the indexing pairs from
%// first coloumns of A and have these as a cell array
A3vals = accumarray(idx,A(:,3),[],@(x) {x})

%// Horizontally concatenate these results to present the final output
out = [num2cell(unqA12) A3vals]

在给定输入上运行的示例产生的输出为 -

out = 
    [1]    [1]    [2x1 double]
    [1]    [4]    [        16]
    [2]    [3]    [        17]
    [3]    [3]    [        87]
    [4]    [4]    [        55]
    [5]    [1]    [       110]
    [6]    [2]    [3x1 double]

或者arrayfun -

%// Find unique rows using the first two columns of A
[unqA12,~,idx] = unique(A(:,1:2),'rows')

%// Use arrayfun to do the groupings instead of accumarray this time 
out = [num2cell(unqA12) arrayfun(@(n) A(idx==n,3),1:max(idx),'Uni',0).']

请注意,第一种方法不会保留第三列元素的顺序,但第二种方法会保留。

【讨论】:

  • 感谢 Divakar 的及时帮助。这非常有用,因为这些是我通常不使用的一些功能,因此非常适合学习!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-20
  • 1970-01-01
  • 1970-01-01
  • 2013-04-10
  • 2011-12-24
  • 2015-07-10
  • 2015-12-09
相关资源
最近更新 更多