[matlab] Create an array of strings

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 don't seem to be able to do it this way.

This question is related to matlab

The answer is


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.


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

Another option:

names = repmat({'Sample Text'}, 10, 1)

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

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.


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

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