Create an array of strings

后端 未结 7 1872
走了就别回头了
走了就别回头了 2020-12-15 03:11

Is it possibe to create an array of strings in MATLAB within a for loop?

For example,

for i=1:10
Names(i)=\'Sample Text\';
end

I do

相关标签:
7条回答
  • 2020-12-15 03:23

    Another option:

    names = repmat({'Sample Text'}, 10, 1)
    
    0 讨论(0)
  • 2020-12-15 03:24

    Another solution to this old question is the new container string array, introduced in Matlab 2016b. From what I read in the official Matlab docs, this container resembles a cell-array and most of the array-related functions should work out of the box. For your case, new solution would be:

    a=repmat('Some text', 10, 1);
    

    This solution resembles a Rich C's solution applied to string array.

    0 讨论(0)
  • 2020-12-15 03:27

    New features have been added to MATLAB recently:

    String arrays were introduced in R2016b (as Budo and gnovice already mentioned):

    String arrays store pieces of text and provide a set of functions for working with text as data. You can index into, reshape, and concatenate strings arrays just as you can with arrays of any other type.

    In addition, starting in R2017a, you can create a string using double quotes "".

    Therefore if your MATLAB version is >= R2017a, the following will do:

    for i = 1:3
        Names(i) = "Sample Text";
    end
    

    Check the output:

    >> Names
    
    Names = 
    
      1×3 string array
    
        "Sample Text"    "Sample Text"    "Sample Text"
    

    No need to deal with cell arrays anymore.

    0 讨论(0)
  • 2020-12-15 03:40

    As already mentioned by Amro, the most concise way to do this is using cell arrays. However, Budo touched on the new string class introduced in version R2016b of MATLAB. Using this new object, you can very easily create an array of strings in a loop as follows:

    for i = 1:10
      Names(i) = string('Sample Text');
    end
    
    0 讨论(0)
  • 2020-12-15 03:42

    one of the simplest ways to create a string matrix is as follow :

    x = [ {'first string'} {'Second parameter} {'Third text'} {'Fourth component'} ]

    0 讨论(0)
  • 2020-12-15 03:43

    You can create a character array that does this via a loop:

    >> for i=1:10
    Names(i,:)='Sample Text';
    end
    >> Names
    
    Names =
    
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    

    However, this would be better implemented using REPMAT:

    >> Names = repmat('Sample Text', 10, 1)
    
    Names =
    
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    Sample Text
    
    0 讨论(0)
提交回复
热议问题