2

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!

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! My problem is, there are more *.txt files in the directory than I want use. Is it possible to say something like "add every file to A which starts with the letter 't' and has the extension '.txt'?
Well, you can obviously do A = dir('t*.txt').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.