Say I have a string in a variable in MATLAB like the following:
this is the first line
this is the second line
this is the third line
I would like to add a fixed string at the beginning of each line. For example:
add_substring(input_string, 'add_this. ')
would output:
add_this. this is the first line
add_this. this is the second line
add_this. this is the third line
I know I can do this by looping through the input string, but I am looking for a more compact (hopefully vectorized) way to do this, perhaps using one of MATLAB built-ins such as arrayfun accumarray.
The
strcatfunction is what you’re looking for. It does vectorized concatenation of strings.With strcat, you need to put
'add_this. 'in a cell ({}) to protect it from having its trailing whitespace stripped, which is strcat’s normal behavior for char inputs.