Search code examples
stringmatlabmatrixcharcell-array

Label Data for Classification in Matlab


I have 2 sets of train data, A and B with different sizes, which I want to use for training the classifier, and I have 2 labels in 2 char variables like,

L1 = 'label A';
L2 = 'label B';

How can I produce appropriate labels ?

I will use cat(1,A,B); to merge data first.

Depending on the size(A,1) and size(B,1), It should be something like,

label = ['label A'
         'label A'
         'label A' 
         .
         .
         'label B'
         'label B'];

Solution

  • Assuming the following:

    na = size(A,1);
    nb = size(B,1);
    

    Here are a few ways to create the cell-array of labels:

    1. repmat

      labels = [repmat({'label A'},na,1); repmat({'label B'},nb,1)];
      
    2. cell-array filling

      labels = cell(na+nb,1);
      labels(1:na)     = {'label A'};
      labels(na+1:end) = {'label B'};
      
    3. cell-array linear indexing

      labels = {'label A'; 'label B'};
      labels = labels([1*ones(na,1); 2*ones(nb,1)]);
      
    4. cell-array linear indexing (another)

      idx = zeros(na+nb,1); idx(nb-1)=1; idx = cumsum(idx)+1;
      labels = {'label A'; 'label B'};
      labels = labels(idx);
      
    5. num2str

      labels = cellstr(num2str((1:(na+nb) > na).' + 'A', 'label %c'));
      
    6. strcat

      idx = [1*ones(na,1); 2*ones(nb,1)];
      labels = strcat({'label '}, char(idx+'A'-1));
      

    ... you get the idea :)


    Note that it's always easy to convert between a cell-array of strings and a char-matrix:

    % from cell-array of strings to a char matrix
    clabels = char(labels);
    
    % from a char matrix to a cell-array of strings
    labels = cellstr(clabels);