问题描述
如果A的第一列重复,我想将A的第二列合并到结束列
I want to merge A's 2nd to end column if A's 1st column is duplicate
来自
A = [2 3 1;
3 4 2;
2 6 8]
到
B{1}=2 3 1 6 8
B{2}=3 4 2 NaN NaN
或
B = [2 3 1 6 8;
3 4 2 NaN NaN]
行排序无关紧要.
我的第一个计划是
A=sortrows(A,1); % sort by 1st col
然后根据第一列将A划分为各种矩阵(即,不同的第一列元素使用不同的矩阵)
and then divide A into various matrices according to 1st col (i.e. different matrix for different 1st column element)
然后horzcat每个矩阵的每个2:end元素.
then horzcat each 2:end elements for each matrices.
,然后以某种方式将它们连接到一个对象中.
and then join them into one object in some way.
这只是我的计划或想象力,尽管我不知道这是否可行.
This is simply my plan or imagination though I can't figure out if this is possible.
推荐答案
以下是一种使您入门的方法.它将使用0
而不是NaN
填充:
Here is a method to get you started. It will pad with 0
instead of NaN
though:
B = sortrows(A,1);
C = B(1,:);
for row = 2:size(B,1)
if B(row,1) == C(end,1)
C(end, end+1:end+2) = B(row, 2:3);
else
C(end+1, 1:3) = B(row, :);
end
end
或者您可以使用单元格数组执行相同的操作,而不必完全填充:
Or you could do the same thing using a cell array and not have to pad at all:
B = sortrows(A,1);
C = {B(1,:)};
for row = 2:size(B,1)
if B(row,1) == C{end}(1)
C{end}(end+1:end+2) = B(row, 2:3);
else
C{end+1} = B(row, :);
end
end
这篇关于合并第二到最后一列以复制第一列中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!