load multiple .txt files and rename them with a for- loop

6 views (last 30 days)
I have a lot of .txt files that I want to import using a for loop:
txt = dir('*txt');
n = length(txt);
for k = 1:n
load(txt(k).name);
end
but the problem is that the .txt files all have vastly different(and some pretty long) names so when trying to use the variables later it becomes rather tedious to refference every single one of them.
So I wonder if i could somehow load these .txt files and rename them for example like:
Area_1
Area_2
.
.
Area _n
  1 Comment
Stephen23
Stephen23 on 22 Oct 2020
"...rename them for example like: Area_1 Area_2 ... Area _n"
That would be about the worst approach:
It would be much neater, simpler, and more efficient to use indexing.

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 22 Oct 2020
Edited: Ameer Hamza on 22 Oct 2020
Loading directly into the workspace is not a good coding practice, and so is naming them dynamically (Area_1, Area_2, ..): https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. The proper way is to load them in a cell array. For example
txt = dir('*txt');
n = length(txt);
Area = cell(1, n);
for k = 1:n
Area{i} = load(txt(k).name);
end
Then access them using brace indexing
Area{1}; % first file
Area{2}; % second file
..
..

More Answers (0)

Categories

Find more on Environment and Settings in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!