我有一个72x3双,看起来像这样
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
Run Code Online (Sandbox Code Playgroud)
我想能够找到基于从第1列和2.实例值的组合从第3列的值,让我们称之为任何值从第1列米,值从第2列Ñ,和从第3列中的相应值p.如果m = 2,n = 3,这将对应于第3行,因此p将为17.如果m = 5,n = 1,这将给出第5行,因此b将为110.请注意,有些情况下,一组m和n将为我们提供两行或更多行.一个例子是m = 1和n1 = 1,它应该从第一行产生24,从第二行产生125.在这种情况下,输出应为[24 125].类似地,组合并且m = 6和n = 2将给出[54 200 63].米的范围从1至6和ñ范围为1〜4的任何组合米和Ñ将产生不超过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]
Run Code Online (Sandbox Code Playgroud)
对给定输入的示例运行产生的输出为 -
out =
[1] [1] [2x1 double]
[1] [4] [ 16]
[2] [3] [ 17]
[3] [3] [ 87]
[4] [4] [ 55]
[5] [1] [ 110]
[6] [2] [3x1 double]
Run Code Online (Sandbox Code Playgroud)
或者与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).']
Run Code Online (Sandbox Code Playgroud)
请注意,第一种方法中不会保留第三列元素的顺序,但第二种方法会保留。