使用预定规则索引矩阵

Indexing a matrix using predetermined rule

我有一个 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=2n=3,这将对应行 3,因此 p 将是 17。如果 m=5n=1,这将给我们第 5 行,因此 b 将是110。请注意,在某些情况下,一组 mn 会给我们两行或更多行。一个例子是 m=1n1=1,它应该从第一行产生 24和第二行的 125。在这种情况下,输出应该是 [24 125]。类似地,m=6n=2 的组合将得到 [54 200 63]m的范围是1到6,n的范围是1到4。m和[的任意组合=19=]n 将产生不超过 4 个输出。谁能帮我解决这个索引问题?

非常感谢。

亚历克斯

一种方法假设 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).']

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

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

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

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

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