필터 지우기
필터 지우기

Avoid using eval on loading struct from a file

조회 수: 3 (최근 30일)
João Araújo
João Araújo 2021년 12월 23일
편집: Stephen23 2021년 12월 23일
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.

답변 (1개)

Stephen23
Stephen23 2021년 12월 23일
편집: Stephen23 2021년 12월 23일
"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.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by