2015-04-19 65 views
1

我有一個非常大的矩陣,看起來像這樣:加入行的矩陣

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

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

我想基質重塑成以下,最好是去掉ID的只出現一次:

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

怎麼是這樣的:http://stackoverflow.com/questions/24841586/create-基於新變量的存在列中的單元格在matlab中 – knedlsepp

+0

也許還會看看'grpstats'。 – knedlsepp

回答

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 
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';