In Python, I can easily join the contents of a list of strings, separated by a set of characters, this way:
>>> L = ["A","B","C"]
>>> string.join(L,"_")
'A_B_C'
In MATLAB, I can concatenate a cell array of strings this way:
>> L = {'A','B','C'};
>> [L{:}] % or strcat(L{:}), with trimming of trailing spaces
ans =
ABC
Is there simple command in MATLAB that mimics the ability of string.join to add a separator character?
I'm aware that this can be done through grotesque constructs such as
[sprintf('%s_',L{1:end-1}), L{end}]
among others, but is there a simpler way?
Edit: From Matlab 2013a on there is a built-in function called strjoin
I don't know of any built-in way, but I use this now (I'm assuming that you want to concatenate a 'cell string' and that you do not want to lose trailing spaces):
L = {' A',' B ','C '};
delimiter = '/';
append_delimiter = @(in) [in delimiter];
tmp = cellfun(append_delimiter, L(1:end-1), 'UniformOutput', false);
result = horzcat(tmp{:}, L{end})
>>> ans =
A B C
Or, the same as a function:
function joined_str = strjoin(in_strings, delimiter)
assert(iscellstr(in_strings), 'strjoin:cellstr', '1st argument: cell string');
assert(ischar(delimiter) && (isvector(delimiter) || isempty(delimiter)), ...
'strjoin:string', '2nd argument: string');
append_delimiter = @(in) [in delimiter];
appended = cellfun(append_delimiter, in_strings(1:end-1), 'UniformOutput', false);
joined_str = horzcat(appended{:}, in_strings{end});
end
>> strjoin({' A ', ' B ', ' C '}, '_')
ans =
A _ B _ C
I don't think there is a build-in function like string.join in MATLAB. Your statement with sprintf is probably the best way how it can be done.
Here is another more recent FileExchange submission - STRJOIN. It probably was based on JOIN from @BenH's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With