gpt4 book ai didi

matlab - 根据另一列的值将矩阵的一列元素分组到元胞数组中

转载 作者:太空宇宙 更新时间:2023-11-03 20:11:00 25 4
gpt4 key购买 nike

一段时间以来,我一直在努力想出一个聪明的方法来做这件事。给定具有以下结构的矩阵(或单元格):

A = [-1  1 
-1 2
1 3
3 5
2 3
2 4
2 7
4 5
5 6
6 7
7 -2 ]

(请注意,上面的矩阵/单元格在两列中均未排序且包含负数)。

如何根据特定列的唯一值对其进行分组。例如。按第二列分组所需的输出类似于:

B{1} = [-1]
B{2} = [-1]
B{3} = [1,2]
B{4} = [2]
B{5} = [3,4]
B{6} = [5]
B{7} = [2,6]
B{-2} = [7]

提前致谢!

最佳答案

您可以使用 accumarray :

[~,~,subs] = unique(A(:,2));
values = accumarray(subs,A(:,1),[],@(x) {x});
ofGroup = accumarray(subs,A(:,2),[],@(x) {x(1)});

out = [ofGroup values]

out = 

[-2] [ 7]
[ 1] [ -1]
[ 2] [ -1]
[ 3] [2x1 double]
[ 4] [ 2]
[ 5] [2x1 double]
[ 6] [ 5]
[ 7] [2x1 double]

如果您真的坚持建议的订单,您可以执行以下操作,但我认为这不是必需的。

% positives
pos = A( A(:,2) >= 0 , :);

[~,~,subs] = unique(pos(:,2));
posvalues = accumarray(subs,pos(:,1),[],@(x) {x});
posofGroup = accumarray(subs,pos(:,2),[],@(x) {x(1)});

% negatives
neg = A( A(:,2) < 0 , :);

[~,~,subs] = unique(neg(:,2));
negvalues = flipud( accumarray(subs,neg(:,1),[],@(x) {x}) );
negofGroup = flipud( accumarray(subs,neg(:,2),[],@(x) {x(1)}) );

out = [posofGroup posvalues; negofGroup negvalues ]

out = 

[ 1] [ -1]
[ 2] [ -1]
[ 3] [2x1 double]
[ 4] [ 2]
[ 5] [2x1 double]
[ 6] [ 5]
[ 7] [2x1 double]
[-2] [ 7]

关于matlab - 根据另一列的值将矩阵的一列元素分组到元胞数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29534749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com