MATLAB: Automatic import of data and rename of array

automatic importdata importimportdataMATLAB

Hello,
I use MatLab since two days and I am a little bit helpless.
My research in google and Mathworks helped me a little bit but a good solution for my problem is still unknown.
I have a lot of measurements in .txt files (Spannung1.txt; Spannung2.txt; …). Is there a way for a automatic data import? The first step I made was the use of a "for loop" (Attachment: "MatLab1.png):
for a = 1:25
importdata("Spannung" + a + ".txt")
end
The import of all .txt files were successfull. The new array was named "ans". Unfortunately, the array "ans" was overwritten with every new import. So the "ans" contains only the information of "Spannung25.txt".
Next step was a test with a loop 1:1 (Attachment: "MatLab2.png"):
for a = 1:1
importdata("Spannung" + a + ".txt")
Spannung1 = ans
clear ans
end
The array was renamed and the old array "ans" was deleted. So i tried to integrate the rename of the array in the loop (Attachment: "MatLab3.png"):
for a = 1:25
importdata("Spannung" + a + ".txt")
Spannung + a = ans
clear ans
end
Here, I have the problem of the unknown Code for a name or rename of the 25 arrays. I hoped, that a new name for an array can be used with the numeric factor "a" like "Spannung + a".
A friend told me, there is a way to generate a 3D-array, where I can combine all data I need from the .txt files. Maybe this a little bit easier but there I have a lack of knowledge.
If someone has a solution or a hint for my problem, I would be happy about a little help.
Greetings,

Best Answer

Creating lots of dynamically named varaibles is not a good approach, and should be avoided.
You should follow the examples in the documentation, which use simple indexing and a cell array:
N = 25;
C = cell(1,N);
for k = 1:N
C{k} = importdata("Spannung" + k + ".txt");
end
If the matrices have compatible sizes then you can concatenate them into one 3D array:
A = cat(3,C{:});