how to sum the elements of the same row in a cell array?

2 ビュー (過去 30 日間)
chocho
chocho 2018 年 12 月 13 日
コメント済み: Image Analyst 2018 年 12 月 13 日
Hello guys,
I ave a cell array of 1450 rows and 2 columns(1450*2)
Some rows in column 1 are repeated but with different contents in column2
How can i get these repeated rows in sigle row with the sum of their contents ?
I appreciate any helps:
Inputs:
Inputs.png
wanted_outputs:
Iwanted_outputs.png
  2 件のコメント
KSSV
KSSV 2018 年 12 月 13 日
Attach the original data....you need to sue unique
chocho
chocho 2018 年 12 月 13 日
I applied unique

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2018 年 12 月 13 日
編集済み: Stephen23 2018 年 12 月 13 日
>> C = {'A','hello';'B','live';'C','cat';'A','world';'B','fast'}‡
C =
'A' 'hello'
'B' 'live'
'C' 'cat'
'A' 'world'
'B' 'fast'
>> [U,~,X] = unique(C(:,1));
>> F = @(n) C(n==X,2).';
>> V = arrayfun(F,1:max(X),'uni',0);
>> Z = [U,V(:)]
Z =
'A' {'hello','world'}
'B' {'live','fast'}
'C' {'cat'}
  3 件のコメント
chocho
chocho 2018 年 12 月 13 日
@Stephen Cobeldick see what i got for my data just tested one line?
'R-HSA-3000171:R-HSA-3000171' 1x4 cell
This row should have
'R-HSA-3000171:R-HSA-3000171' 'PDGFB, TTR, COL4A6,LAMA1,COL4A5 ,COL11A2,COL3A1'
Yr example is sample.
Stephen23
Stephen23 2018 年 12 月 13 日
編集済み: Stephen23 2018 年 12 月 13 日
@chocho: You can easily concatenate those character vectors together, if that is what you want to do, just change the anonymous function:
>> F = @(n) [C{n==X,2}];
>> V = arrayfun(F,1:max(X),'uni',0);
>> Z = [U,V(:)]
Z =
'A' 'helloworld'
'B' 'livefast'
'C' 'cat'
Or perhaps you want to join them with commas, this is also easy:
>> F = @(n) sprintf('%s, ',C{n==X,2});
>> V = arrayfun(F,1:max(X),'uni',0);
>> Z = [U,strtrim(V(:))]
Z =
'A' 'hello, world,'
'B' 'live, fast,'
'C' 'cat,'

サインインしてコメントする。

その他の回答 (1 件)

KSSV
KSSV 2018 年 12 月 13 日
編集済み: KSSV 2018 年 12 月 13 日
C = cell(5,2) ;
C{1,1} = 'apple' ; C{1,2} = 'red' ;
C{2,1} = 'apple' ; C{2,2} = 'round' ;
C{3,1} = 'grapes' ; C{3,2} = 'green' ;
C{4,1} = 'strawberry' ; C{4,2} = 'sweet' ;
C{5,1} = 'grapes' ; C{5,2} = 'small' ;
%
[c,ia,ib] = unique([C(:,1)]) ;
iwant = cell(length(c),2) ;
for i = 1:length(c)
iwant{i,1} = c{i} ;
iwant{i,2} = strjoin(C(ib==i,2)) ;
end
  4 件のコメント
chocho
chocho 2018 年 12 月 13 日
KSSV Could you update yr code to got my iwant plz i want the ',' between in ?
without it i can't continue my work!
Image Analyst
Image Analyst 2018 年 12 月 13 日
I see that he asked for your data (which you could attach in a .mat file with the paper clip icon) and you chose not to. If you make it easy for people to help you, not hard, then you'd get an answer sooner - you'd probably have had the solution by now.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangePolar Plots についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by