Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array of strings

Tags:

matlab

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.

like image 414
Brian Avatar asked Aug 17 '11 23:08

Brian


People also ask

How do you create an array of strings?

Create String Arrays from Variables Each element of a string array contains a 1-by-n sequence of characters. You can create a string using double quotes. As an alternative, you can convert a character vector to a string using the string function. chr is a 1-by-17 character vector.

Can we create an array of string?

We can have an array with strings as its elements. Thus, we can define a String Array as an array holding a fixed number of strings or string values. String array is one structure that is most commonly used in Java. If you remember, even the argument of the 'main' function in Java is a String Array.

How do I make a string array in Python?

String[] ar = new String[size]; Arrays. fill(ar,"");

How do you create an array?

You can make an array of int s, double s, or any other type, but all the values in an array must have the same type. To create an array, you have to declare a variable with an array type and then create the array itself. Array types look like other Java types, except they are followed by square brackets ( [] ).


3 Answers

You need to use cell-arrays:

names = cell(10,1);
for i=1:10
    names{i} = ['Sample Text ' num2str(i)];
end
like image 63
Amro Avatar answered Oct 08 '22 04:10

Amro


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
like image 45
b3. Avatar answered Oct 08 '22 04:10

b3.


Another option:

names = repmat({'Sample Text'}, 10, 1)
like image 36
Rich C Avatar answered Oct 08 '22 02:10

Rich C