Baloo
Baloo

Reputation: 221

read files with loop in MATLAB

I am reading all files from a directory. But then I want to loop over it and load the files with the number of iterator of the loop, like this

A = dir('*.txt');
for i=1:size(A)
   text = function('Text'+i+'.txt');
end

So my problem is, I can't find the right syntax to get the text file at the i-position. Thanks!

Upvotes: 2

Views: 482

Answers (1)

sebastian
sebastian

Reputation: 9696

You can't simply add strings like 'Text' and numbers i. You'll have to convert i to a string first and then concatenate the three:

text = function(['Text', num2str(i), '.txt']);

Alternatively, my preferred solution would be to use sprintf:

text = function(sprintf('Text%i.txt', i));

sprintf will replace the %i part in the string by the integer-representation of i.

EDIT:

Re-reading your question, you might be better off using the information from dir instead of building your own filenames:

text = function(A(i).name);

The structure A will contain information on every file - including its name. This would make your code somewhat more stable.

Upvotes: 5

Related Questions