Concatenate two cell arrays of strings with a space in between?

北战南征 提交于 2019-12-30 11:00:18

问题


How can I concatenate:

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

with

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

with a space in between to get:

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

Is there a fast non-looping way?


回答1:


You can use strcat(), although it performs a loop:

strcat(A,{' '}, B)

where the blank is preserved by enclosing it within a cell.

Alternatively, FEX:CStrCatStr is a mex routine which achieves a 10x speedup (depending on testing environment):

CStrCatStr(A,' ', B)



回答2:


A faster (albeit less elegant) alternative to strcat that concatenates strings is a combination of the sprintf and textscan commands:

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

Benchmark

Here's the benchmark code:

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

The results are:

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



回答3:


You can do that using cellfun:

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

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


来源:https://stackoverflow.com/questions/16743093/concatenate-two-cell-arrays-of-strings-with-a-space-in-between

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!