加入Matrix中的行

时间:2015-04-19 21:20:03

标签: matlab

我有一个非常大的矩阵,看起来像这样:

id,value
1,434
2,454353
1,4353
3,3432
3,4323
[...]

最多可以有2行具有相同的ID。

我想将矩阵重新整形为以下内容,最好删除仅出现一次的id:

id,value1,value2
1,434,4353
3,3432,4323
[...]

2 个答案:

答案 0 :(得分:1)

以下是使用accumarray标识共享相同索引的值的替代方法。代码已注释,您可以查看每个中间输出以查看到底发生了什么。

clear
clc

%// Create matrix with your data
id = [1;2;1;3;3];
value = [434 ;454353;4353;3432;4323];

M = [id value]

%// Find unique indices to build final output.
UniqueIdx = unique(M(:,1),'rows')

%// Find values corresponding to every index. Use cell array to account for different sized outputs.
NewM = accumarray(id,value,[],@(x) {x})

%// Get number of elements 
NumElements = cellfun(@(x) size(x,1),NewM)

%// Discard rows having orphan index.
NewM(NumElements==1) = [];
UniqueIdx(NumElements==1) = [];

%// Build Output.
Results = [UniqueIdx NewM{1} NewM{2}]

输出。我无法使用函数table来构建一个不错的输出,但是如果你这样做,结果会更好看:)

Results =

           1         434        3432
           3        4353        4323

答案 1 :(得分:0)

这段代码完成了根据id排序矩阵并删除孤儿的有趣工作。

x = sortrows(x,1); % sort x according to index
idx = x(:,1);
idxs = 1:max(idx);
rm = idxs(hist(idx, idxs) == 1); %find orphans
x( ismember(x(:,1),rm), : ) = [] %remove orphans

这最后一部分只是按照你想要的方式塑造数组

y = reshape(x', 4, []);
y( 3, : ) = [];
y=y';