Search code examples
matlabcell-array

Concatenating two column values from a cell array


I have a cell array:

cellArray = {
   '123' 'BC' 'other value';
   '124' 'BC' 'other value';
   '125' 'BC' 'other value';
   '126' 'BC' 'other value';
}

I would like to obtain this:

cellArray = {
   '123 BC' 'other value';
   '124 BC' 'other value';
   '125 BC' 'other value';
   '126 BC' 'other value';
}

As you can see the second column is now concatenated to the first... Any suggestion?


Solution

  • Looks like strcat plus standard cell array concatenation can do it:

    x = [strcat(cellArray(:,1), {' '}, cellArray(:,2)) cellArray(:,3)]
    

    The only trick is that the middle space character needs to be in a cell, otherwise strcat tries to "help" by removing trailing spaces. See help strcat for an explanation.