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.
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.
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.
String[] ar = new String[size]; Arrays. fill(ar,"");
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 ( [] ).
You need to use cell-arrays:
names = cell(10,1);
for i=1:10
names{i} = ['Sample Text ' num2str(i)];
end
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 option:
names = repmat({'Sample Text'}, 10, 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With