How can I concatenate strings in a cell array with spaces between them in MATLAB?

Martin08 picture Martin08 · Mar 13, 2011 · Viewed 19.3k times · Source

I want to concatenate (padding with spaces) the strings in a cell array {'a', 'b'} to give a single string 'a b'. How can I do this in MATLAB?

Answer

Alex picture Alex · Mar 13, 2011

You can cheat a bit, by using the cell array as a set of argument to the sprintf function, then cleaning up the extra spaces with strtrim:

 strs = {'a', 'b', 'c'};
 strs_spaces = sprintf('%s ' ,strs{:});
 trimmed = strtrim(strs_spaces);

Dirty, but I like it...