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?
6 Answers
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...
2 Comments
strjoin is only available on Matlab R2013a and later so this solution is nice if you are working with an older version.size_info = sprintf('%dx' , size( var ) ) and removing the last char: size_info = size_info(1:end-1);matlab have a function to do this,
ref:
http://www.mathworks.com/help/matlab/ref/strjoin.html
strjoin
Join strings in cell array into single string
Syntax
str = strjoin(C) example
str = strjoin(C,delimiter)
Ex:
Join List of Words with Whitespace
Join individual strings in a cell array of strings, C, with a single space.
C = {'one','two','three'};
str = strjoin(C)
str =
one two three
1 Comment
You can accomplish this using the function STRCAT to append blanks to all but the last cell of your cell array and then concatenate all the strings together:
>> strCell = {'a' 'b' 'c' 'd' 'e'};
>> nCells = numel(strCell);
>> strCell(1:nCells-1) = strcat(strCell(1:nCells-1),{' '});
>> fullString = [strCell{:}]
fullString =
a b c d e
Comments
Both join and strjoin are introduced in R2013a. However, the mathworks site about strjoin reads:
Starting in R2016b, the
joinfunction is recommended to join elements of a string array.
>> C = {'one','two','three'};
>> join(C) %same result as: >> join(C, ' ')
ans =
string
"one two three"
>> join(C, ', and-ah ')
ans =
string
"one, and-ah two, and-ah three"
Personally I like Alex' solution as well, as older versions of Matlab are abundant in research groups around the world.
Comments
You can use MATLAB's strjoin function that takes two arguments: an array of strings and a delimiter. If the strings are not in an array format, MATLAB will raise an error. In addition to the answers above, this might be straightforward to others but if you're not an expert in MATLAB code like me, here's how you can concatenate strings given they are not in an array:
a = 'A';
b = 'B';
ab = strjoin({a, b}, '--');
This results in:
A--B