Reputation: 27392
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.
Upvotes: 38
Views: 136730
Reputation: 2575
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.
Upvotes: 3
Reputation: 817
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.
Upvotes: 2
Reputation: 125854
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
Upvotes: 1
Reputation: 11
one of the simplest ways to create a string matrix is as follow :
x = [ {'first string'} {'Second parameter} {'Third text'} {'Fourth component'} ]
Upvotes: 0
Reputation: 7155
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
Upvotes: 9
Reputation: 124543
You need to use cell-arrays:
names = cell(10,1);
for i=1:10
names{i} = ['Sample Text ' num2str(i)];
end
Upvotes: 48