Matlab 在矩阵中连接行
我有一个非常大的矩阵,看起来像这样:Matlab 在矩阵中连接行,matlab,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 [...] 这段代码完成了一项有趣的工作,即根据id对矩阵进行排序,并删除孤立项 x = sortrows(x,1); % sort x according to index idx = x(
id,value
1,434
2,454353
1,4353
3,3432
3,4323
[...]
最多可以有2行具有相同的id
我想将矩阵重塑为以下形状,最好删除只出现一次的id:
id,value1,value2
1,434,4353
3,3432,4323
[...]
这段代码完成了一项有趣的工作,即根据
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';
下面是一个替代方法,用于标识共享同一索引的值。代码会被注释,您可以查看每个中介输出,以了解到底发生了什么
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
来构建一个好的输出,但是如果您这样做,结果会更好:)
像这样的东西怎么样:也许还可以看看
grpstats
。
Results =
1 434 3432
3 4353 4323