在MATLAB中为字符串中的每一行添加子字符串

Ame*_*ina 1 matlab

假设我在MATLAB中的变量中有一个字符串,如下所示:

this is the first line 
this is the second line 
this is the third line
Run Code Online (Sandbox Code Playgroud)

我想每行的开头添加一个固定的字符串.例如:

add_substring(input_string, 'add_this. ') 
Run Code Online (Sandbox Code Playgroud)

输出:

add_this. this is the first line 
add_this. this is the second line 
add_this. this is the third line
Run Code Online (Sandbox Code Playgroud)

我知道我可以通过循环输入字符串来实现这一点,但我正在寻找一种更紧凑(希望是矢量化)的方法来实现这一点,可能使用MATLAB内置函数之一arrayfun accumarray.

And*_*nke 6

strcat功能正是您所需要的.它执行字符串的矢量化连接.

strs = {
    'this is the first line'
    'this is the second line'
    'this is the third line'
    }
strcat({'add_this. '}, strs)
Run Code Online (Sandbox Code Playgroud)

使用strcat,你需要放入'add_this. '一个cell({})来保护它不被剥离尾部空格,这是strcat对char输入的正常行为.