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

前端 未结 3 739
情深已故
情深已故 2021-01-14 16:02

How can I concatenate:

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

with

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

with a

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-14 16:59

    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.
    

提交回复
热议问题