Search code examples
stringmatlabconcatenationcell-array

Appending string column to number column


How to append a column of strings to a column of numbers in MATLAB?

For example, I have the string column wrds and the number column occurs

wrds={'the' 'of' 'to' 'and'}'; occurs=[103 89 55 20]';

And I want to put them side by side so that they display like this:

'the' 103
'of'   89
'to'   55
'and'   20

You would thing that this would do the trick:

out={wrds occurs}

But the output I get when I enter this is:

out =
{4x1 cell}    [4x1 double]

Which tells me nothing. How can I do this so that I get to see the actual display of strings and numbers?


Solution

  • Convert the numeric array into a cell array and concatenate:

    >> out = [wrds(:) num2cell(occurs)]
    out = 
        'the'    [103]
        'of'     [ 89]
        'to'     [ 55]
        'and'    [ 20]
    

    As a speedier alternative to num2cell, I'd suggest sprintfc: out = [wrds(:) sprintfc('%d',occurs(:))].