Reputation: 11
I want to create an array of character vectors like this:
'abc1', 'abc12', 'abc9'
Two questions: How do I initialize this, and how do I reference each element?
I want to read a bunch of values from a file and create the array from each line. The file will look like this:
abc1 abc12 abc9
Once read in, I want to use each character vector like the following:
for i in <mumble>
fprintf(" element = %s\n", <mumble-one-element>)
end
(printing is just the easiest way to represent that I want to access each element in the array.)
I'm a newbie to MATLAB and am having a hard time translating array usage to other languages I know.
Upvotes: 0
Views: 67
Reputation: 1556
Use fgetl
to read a line from the file and strsplit
to create a cell array.
Suppose test.txt is your file, which has the following data:
abc1 abc12 abc9
abc4 abc5 abc6
Read the file line by line and create the corresponding cell array:
fileID = fopen('test.txt');
tline = fgetl(fileID);
while ischar(tline)
cell_array = strsplit(tline);
for i = 1:length(cell_array)
fprintf(" element = %s\n", cell_array{i});
end
fprintf("\n");
tline = fgetl(fileID);
end
fclose(fileID);
Output:
element = abc1
element = abc12
element = abc9
element = abc4
element = abc5
element = abc6
Upvotes: 2