2012-01-18 275 views
1

说我有这样一个变量的字符串在MATLAB如下:添加一个字符串到每一行,在MATLAB字符串

this is the first line 
this is the second line 
this is the third line 

我想在每个月初加一个固定的字符串线。例如:

add_substring(input_string, 'add_this. ') 

将输出:

add_this. this is the first line 
add_this. this is the second line 
add_this. this is the third line 

我知道我可以通过输入字符串循环做到这一点,但我要寻找一个更紧凑的(希望矢量)的方式来做到这一点,也许使用MATLAB内建的一个例如arrayfunaccumarray

回答

6

strcat功能就是你要找的。它矢量化了字符串的连接。

strs = { 
    'this is the first line' 
    'this is the second line' 
    'this is the third line' 
    } 
strcat({'add_this. '}, strs) 

随着strcat的,你需要把'add_this. '在细胞({}),以保护其免受其剥去其尾随的空白,这是字符输入的strcat的正常行为。

+0

输入字符串在技术上不是一个单元格数组,而是一个char字符串,但是我可以使用'[input_string,〜] = regexp(input_string,'\ n','split')将其转换为一个'' – 2012-01-18 16:07:39

+0

'Strcat'工作也在'char'输入上。但是你仍然需要做这样的分割,因为多个字符串作为'char'被存储在一个2-d char矩阵中的单独行;看起来像你的输入是一个单一的多行字符串。 – 2012-01-18 16:26:56

0

假设你的字符串存储在一个单元格数组中,那么cellfun将会做你想做的事情,例如,

s = {'this is the first line', 'this is the second line', 'this is the third line'}; 
prefix = 'add_this. '; 
res = cellfun(@(str) strcat(prefix, str), s, 'UniformOutput', false); 
+0

检查'res'输出;前缀正在被剥离。 – 2012-01-18 15:35:26

相关问题