连接两个字符串的单元格数组,其间有空格?

时间:2013-05-24 20:24:57

标签: matlab string-concatenation cell-array

我如何连接:

A = {'hello'; 'hi'; 'hey'}

B = {'Ben'; 'Karen'; 'Lisa'}

中间有空格得到:

C = {'hello Ben'; 'hi Karen'; 'hey Lisa'}

是否存在快速非循环方式?

3 个答案:

答案 0 :(得分:3)

您可以使用strcat(),但它会执行循环:

strcat(A,{' '}, B)

通过将空白封闭在单元格中来保留空白。

或者,FEX:CStrCatStr是一个mex例程,可实现10倍的加速(取决于测试环境):

CStrCatStr(A,' ', B)

答案 1 :(得分:2)

strcat连接字符串的更快(尽管不太优雅)的替代方案是sprintftextscan命令的组合:

C = [A; B];
C = textscan(sprintf('%s %s\n', C{:}), '%s', 'delimiter', '\n');

基准

以下是基准代码:

A = {'hello' ; 'hi' ; 'hey'};
B = {'Ben' ; 'Karen' ; 'Lisa'};

%// Solution with strcat
tic
for k = 1:1000
    C1 = strcat(A, ' ', B);
end
toc

%// Solution with sprintf and textscan
tic
for k = 1:1000
    C2 = [A; B];
    C2 = textscan(sprintf('%s %s\n', C2{:}), '%s', 'delimiter', '\n');
end
toc

结果是:

Elapsed time is 0.022659 seconds.
Elapsed time is 0.006011 seconds.

答案 2 :(得分:1)

你可以使用cellfun:

cellfun(@(x,y) [x, ' ', y], A, B, 'UniformOutput', false)

ans = 
{
  [1,1] = hello Ben
  [2,1] = hi Karen
  [3,1] = hey Lisa
}