How to create dynamic field reference in a structure
Show older comments
Hi,
I am trying to read lines from a text file generated during a simulation. For ex
Text file has information as follows
$------------------------------------------------------------------------REQUEST
[REQUEST]
NAME = 'driver_demands'
ID = 1
X = 'steering'
Y = 'throttle'
Z = 'brake'
R1 = 'gear_position'
R2 = 'clutch'
X_UNITS = 'angle'
Z_UNITS = 'force'
$------------------------------------------------------------------------REQUEST
[REQUEST]
NAME = 'sse_outputs'
ID = 2
X = 'yaw_moment'
Y = 'lateral_force'
X_UNITS = 'torque'
Y_UNITS = 'force'
$------------------------------------------------------------------------REQUEST
I would like to create a structure with dynamic field names. Req.info is a structure with 4 fields ID, NAME, Marker_Data, Complete_Data
I would like to update Req.info Such that Req.info(1).Complete_Data =
NAME: 'driver_demands'
ID: 1
X: 'steering'
Y: 'throttle'
Z: 'brake'
R1: 'gear_position'
R2: 'clutch'
X_UNITS: 'angle'
Z_UNITS: 'force'
Where
Req.info(1).Complete_Data.X
Req.info(1).Complete_Data.Y
Req.info(1).Complete_Data.Z... (Fields X,Y,Z,.... are created dynamically)
Such that Req.info(1).Complete_Data.X = steering and so on...
I have tried with following code but could not succeed.
while ~strncmp(zeile,'$', 1)
line = fgetl(fid);
[Marker_name, Marker_data]= strread(line, '%s''%s', 'delimiter','=');
Marker_name = strtrim(Marker_name);
Marker_data = strtrim(Marker_data);
Marker_data = Marker_data (1:end-1);
eval(['Req.info(', num2str(i), ').Complete_Data.', char(Marker_name), ' = ', char(Marker_name), ';']);
end
This is the first time am dealing with data import functions. Please help me out..
Thanx a lot..
Accepted Answer
More Answers (1)
Walter Roberson
on 18 Jun 2012
Req.info(i).Complete_Data.(Marker_name) = Marker_data;
2 Comments
Udayteja
on 18 Jun 2012
Walter Roberson
on 18 Jun 2012
At the line before that,
fprintf(1, '|%s|\n', Marker_name);
length(Marker_name)
and check to see whether Marker_name has any blanks or any characters other than A-Z, a-z, 0-9, and underscore. If it has any of those, then it is not a valid name for a structure field.
Categories
Find more on Testing Frameworks in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!