Avoid using eval on loading struct from a file
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hello, I am trying to load data from files in a function like such:
function plotxx (file1,file2)
load(file1);
filename1=strsplit(file1,'.');
struct1=eval(filename1{1});
load(file2);
filename2=(strsplit(file2,'.'));
struct2=eval(filename2{1});
time1=struct1.X.Data;
p1=struct1.Y(2).Data;
p2=struct2.Y(2).Data;
Each file contains one struct of the same type with a different name which then I want to use in my code. As the names of the structures are the filenames, I copied the contents of the structs to 'struct1' and 'struct2' using eval.
As using eval is not the optimal way, is there any other way to do this?
Thank you in advance.
0 Commenti
Risposte (1)
Stephen23
il 23 Dic 2021
Modificato: Stephen23
il 23 Dic 2021
"As using eval is not the optimal way, is there any other way to do this?"
Always LOAD into an output variable (which is a scalar structure):
S = load(..);
And then access the appropriate field/s. If there are multiple variables (i.e. fields), then this might not be a trivial task. However if there is exactly one variable per file then you can get it without knowing its name:
C = struct2cell(load(..));
D = C{1}
Note that having different variable names is sub-optimal data design (as you are finding out now), by far the best solution is to save the files using exactly the same variable names. Then your code would be simple and robust, and you would not have this problem.
0 Commenti
Vedere anche
Categorie
Scopri di più su Structures in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!