Clear Filters
Clear Filters

Info

This question is closed. Reopen it to edit or answer.

Group data by 2 condiitions

3 views (last 30 days)
Lusine
Lusine on 18 Oct 2012
Closed: MATLAB Answer Bot on 20 Aug 2021
Hi everyone I have data like this
A Type1 10
A Type2 10
A Type1 25
B Type2 12
B Type1 36
C Type1 45
C Type3 17
C Type2 40
and want to group them in a matrix like this
A B C
Type1 35 36 45
Type2 10 12 40
Type3 0 0 17
where the numbers are the sum of coresponding numbers. Can anyone help me with this?

Answers (3)

Azzi Abdelmalek
Azzi Abdelmalek on 18 Oct 2012
Edited: Azzi Abdelmalek on 18 Oct 2012
A={'A Type1 10' 'A Type1 10' 'A Type1 25' 'B Type2 12' 'B Type1 36' 'C Type1 45' }
B=cellfun(@(x) regexp(x,' ','split'),A,'un',0)'
M=cellfun(@(x) x(1),B)
type=cellfun(@(x) x(2),B)
Num=cellfun(@(x) x(3),B)
  1 Comment
Lusine
Lusine on 18 Oct 2012
Thaks for the answer but I needed something different, I need to convert data into matrix where the fist element which is 35 = 10+25 that is for A data which are Type1.

Azzi Abdelmalek
Azzi Abdelmalek on 18 Oct 2012
Edited: Azzi Abdelmalek on 18 Oct 2012
A={'A Type1 10'
'A Type2 10'
'A Type1 25'
'B Type2 12'
'B Type1 36'
'C Type1 45'
'C Type3 17'
'C Type2 40 '}
B=cellfun(@(x) regexp(x,' ','split'),A,'un',0)
M=cellfun(@(x) x(1),B)
type=cellfun(@(x) x(2),B)
Num=cellfun(@(x) x(3),B)
M1=unique(M)
type1=unique(type)
out=cell(numel(type1),numel(M1))
for k=1:numel(M)
ii=find(ismember(type1,type(k)))
jj= find(ismember(M1,M(k)))
out(ii,jj)=Num(k);
end
out=[['/' M1']; type1 out ]

Sean de Wolski
Sean de Wolski on 18 Oct 2012
I don't know how you have your data stored but if you can get it into the format below (either with xlsread or whatever) then you can use accumarray
letter = cellstr(('AAABBCCC')');
Type = {'Type1','Type2','Type1','Type2','Type1','Type1','Type3','Type2'}';
value = [10 10 25 12 36 45 17 40];
%Unique values
[uL,~,lidx] = unique(letter);
[uT,~,Tidx] = unique(Type);
M = accumarray([Tidx lidx],value); %build matrix
If you have the Statistics Toolbox then you can build a dataset that completely resembles your goal:
DS = mat2dataset(M,'VarNames',uL','ObsNames',uT')

This question is closed.

Community Treasure Hunt

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

Start Hunting!