Home > Mobile >  Group data in a cell array
Group data in a cell array

Time:05-17

I have the following data:

Names={A1 A2 B1 B2 C1 C2 C3}
Doserate=(2.2 3.4 6.4 3.4 2.3 4.5 7.5)
Time=(5 7.8 9 3.5 10.2 5.6 7.8)

The order of Doserate and Time is such they correspond to Names. I would like to make groups starting with the same letter so that I can perform calculations using Doserate and Time corresponding to that group. Names can vary to even more letters (A-Z) or more numbers like (A1-A30).

How can I group these entries?

CodePudding user response:

Names={'A1' 'A2' 'B1' 'B2' 'C1' 'C2' 'C3'};
first_letter = blanks(numel(Names));
for ii = 1:numel(Names)
    first_letter(ii) = Names{ii}(1);  % Grab the first letter
end
[a, b, c] = unique(first_letter)

a =

ABC


b =

     2     4     7


c =

     1     1     2     2     3     3     3

You can use a loop to extract the first character in each cell entry (you can probably use cellfun() as well) and then a call to unique() to extract the unique characters. Its third output, named c in my example, will be your groups. Thus Doserate(c(c==2)) will return all Doserate entries where Names start with B.

CodePudding user response:

To extract one or more letters from the start of your names, you can use regex:

Names = {'A1' 'A2' 'B1' 'B2' 'C1' 'C2' 'C3'};
N = regexp( Names, '^[a-zA-Z] ', 'match', 'once' )
% >> N = {'A', 'A', 'B', 'B', 'C', 'C', 'C'};

Then you can use findgroups to group them

[gidx,gnames] = findgroups(N)

gidx =
     1     1     2     2     3     3     3
gnames =
    {'A', 'B', 'C'}

i.e. now anything where gidx == 2 matches the group 'B' (2nd element in gnames).

  • Related