How can I concatenate strings in a cell array with spaces between them in MATLAB?

后端 未结 5 739
青春惊慌失措
青春惊慌失措 2020-12-15 23:34

I want to concatenate (padding with spaces) the strings in a cell array {\'a\', \'b\'} to give a single string \'a b\'. How can I do this in MATLAB

相关标签:
5条回答
  • 2020-12-15 23:59

    You can accomplish this using the function STRCAT to append blanks to all but the last cell of your cell array and then concatenate all the strings together:

    >> strCell = {'a' 'b' 'c' 'd' 'e'};
    >> nCells = numel(strCell);
    >> strCell(1:nCells-1) = strcat(strCell(1:nCells-1),{' '});
    >> fullString = [strCell{:}]
    
    fullString =
    
    a b c d e
    
    0 讨论(0)
  • 2020-12-16 00:02

    Small improvement (?) on the answer by Alex

    strs = {'a','b','c'};  
    strs_spaces = [strs{1} sprintf(' %s', strs{2:end})];
    
    0 讨论(0)
  • 2020-12-16 00:08

    You can cheat a bit, by using the cell array as a set of argument to the sprintf function, then cleaning up the extra spaces with strtrim:

     strs = {'a', 'b', 'c'};
     strs_spaces = sprintf('%s ' ,strs{:});
     trimmed = strtrim(strs_spaces);
    

    Dirty, but I like it...

    0 讨论(0)
  • 2020-12-16 00:08

    matlab have a function to do this,

    ref:

    strjoin

    http://www.mathworks.com/help/matlab/ref/strjoin.html

    strjoin

    Join strings in cell array into single string

    Syntax

    str = strjoin(C) example
    
    str = strjoin(C,delimiter)
    

    Ex:

    Join List of Words with Whitespace

    Join individual strings in a cell array of strings, C, with a single space.

    C = {'one','two','three'};
    
    str = strjoin(C)
    
    str =
    
    one two three
    
    0 讨论(0)
  • 2020-12-16 00:12

    Both join and strjoin are introduced in R2013a. However, the mathworks site about strjoin reads:

    Starting in R2016b, the join function is recommended to join elements of a string array.

    >> C = {'one','two','three'};
    >> join(C) %same result as: >> join(C, ' ')
    
    ans = 
    
      string
    
        "one two three"
    
    >> join(C, ', and-ah ')
    
    ans = 
    
      string
    
        "one, and-ah two, and-ah three"
    

    Personally I like Alex' solution as well, as older versions of Matlab are abundant in research groups around the world.

    0 讨论(0)
提交回复
热议问题