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

1 Ansicht (letzte 30 Tage)
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 Kommentar
Stephen23
Stephen23 am 22 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 22 Okt. 2020
Bearbeitet: Ameer Hamza am 22 Okt. 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
..
..

Weitere Antworten (0)

Kategorien

Mehr zu Environment and Settings finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by