Loading files by replacing some part of the name with a variable
5 次查看(过去 30 天)
显示 更早的评论
Hi, I want to load a bunch of files in my workspace. There all name simmilarly and there's a number counting up, but its not just at the end of the Filename, so just replacing it with 'i' doesn't work.
Any ideas?
The 'i' in the file name are two digits. Starting with '01' and ending with '41'
I found a Video of someone explaining a similar issue, but I wasn't able to adapt the solution to my code.
for i = 01:41
FileName = 'GNSS_Validierung_0i.mat';
FolderName = 'C:\Users\Admin\Documents\BA\MATLAB\Routenplanung\versuchsdaten_maxi';
File = fullfile(FolderName, FileName);
load(File);
x_DIY_flip = GNSS_Validierung_0i.Y(23).Data';
y_DIY_flip = GNSS_Validierung_0i.Y(25).Data';
x_ppm_flip = GNSS_Validierung_0i.Y(24).Data';
y_ppm_flip = GNSS_Validierung_0i.Y(26).Data';
.
.
.
end
2 个评论
Dyuman Joshi
2023-12-4
Have a look at this - https://in.mathworks.com/help/matlab/import_export/process-a-sequence-of-files.html
How do you get the data i.e. all the mat file, in the manner (using numbers in the name i.e. dynamically naming them) you have now? Is the data output from some code?
回答(2 个)
Matt J
2023-12-4
编辑:Matt J
2023-12-4
Pre-generate all of the filenames and loop over them.
FileNames = compose("GNSS_Validierung_%.2d",(1:41)' )
6 个评论
Matt J
2023-12-4
@Stephen23 Good point. I've removed the .mat sub-string from the code I proposed (it was never necessary).
Stephen23
2023-12-4
编辑:Stephen23
2023-12-4
Do NOT name each variable dynamically. Unless you want to force yourself into writing slow, complex, inefficient, insecure, obfuscated code that is buggy and hard to debug.
Always LOAD into an output variable (which is a scalar structure). The your data-access problems are easily avoided:
P = 'C:\Users\Admin\Documents\BA\MATLAB\Routenplanung\versuchsdaten_maxi';
for k = 01:41
F = sprintf('GNSS_Validierung_%02d.mat',k);
C = struct2cell(load(fullfile(P,F));
assert(isscalar(C),'Exactly one variable is allowed!')
x_DIY_flip = C{1}.Y(23).Data.';
y_DIY_flip = C{1}.Y(25).Data.';
x_ppm_flip = C{1}.Y(24).Data.';
y_ppm_flip = C{1}.Y(26).Data.';
.
.
.
end
Note that your code would be simpler, more efficient, and much more robust if the variable names were exactly the same in every MAT file. That is to say, the data you have been given is badly designed.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!