Generate Field Names from Variables While Accessing Elements of a Nonscalar Structure Array
1 view (last 30 days)
Show older comments
I have a top-level 1x20 structure arrray with 10 fields which is generated using code similar to below with no problems (this is an extract of a larger script).
for nLap = 1:R2(nDriver).Laps
R2(nDriver).LapData(nLap).LapTime = sessions.R2.Sectors.(nDriverStr).LapTime(nLap);
R2(nDriver).LapData(nLap).SectoR2 = sessions.R2.Sectors.(nDriverStr).S1Time(nLap);
R2(nDriver).LapData(nLap).Sector2 = sessions.R2.Sectors.(nDriverStr).S2Time(nLap);
R2(nDriver).LapData(nLap).Sector3 = sessions.R2.Sectors.(nDriverStr).S3Time(nLap);
R2(nDriver).LapData(nLap).TIS = sessions.R2.Sectors.(nDriverStr).TiS(nLap);
end
However, I need to run this for many other structures by replacing the 'R2' to 'R1' for example.
Previously, I have done that in the same way that the (nDriverStr) variable in used to enter a field within the structure, however this does not seem to work when I am already referencing a row within the structure such as:
(R)(nDriver).LapData(nLap).LapTime = sessions.(R).Sectors.(nDriverStr).LapTime(nLap);
Is there a way to do this using R as a variable string which loops through "R1", "R2", "R3" for example?
4 Comments
Steven Lord
on 30 Jun 2022
What about the naming here makes these badly named?
name = 'why, x'; % Specified by user or written as a file name?
eval([name '.foo = 1'])
Now picture a system or quit call in place of the why call.
Answers (1)
Matt J
on 30 Jun 2022
Why not a 2D struct array,
R(nDriver,1).LapData(nLap).LapTime
R(nDriver,2).LapData(nLap).LapTime
R(nDriver,3).LapData(nLap).LapTime
0 Comments
See Also
Categories
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!