Reference changing field names in loop

47 views (last 30 days)
Hello all,
I'm working with data coming from 32 probes of the same build, which comes in the form of *.tdms files, one file for every probe. I'm using a Script from this forum to extract the information into a structure:
for i=1:32
probe(i) = TDMS_getStruct(filename(i));
end
This returns a structure called "probe" with the fields "Property" and "chanel_x", where x is the number of the corresponding probe, and each of these fields has a few subfields. As an example, the data I'm looking for, in the case of the first probe and second probe respectivly, is found in:
probe(1).channel_1.data % data from probe 1
probe(2).channel_2.data % data from probe 2
My problem is, that I haven't found a way to access that data in a loop, because the field name "channel_x" is different for every probe and I havn't found a solution yet to call this field for every probe. I'm looking for something like:
for i=1:32
data(i) = probe(i).channel_(i).data; %this obviously doesn't work, this is just to show that I need the field name to change in every loop too
end
I know this is similar to changing a variable in every loop, which isn't good programming practice, but here I'm in the situation that I can't do anything about the change in field name for every probe (that's just the way I get the data), so I'm hoping someone here can help me with this issue.

Accepted Answer

Arthur Roué
Arthur Roué on 24 Jul 2020
Edited: Arthur Roué on 24 Jul 2020
You can access a field dynamically by putting the name of the field in a var in brackets.
for i=1:32
field = sprintf('channel_%d', i)
data(i) = probe(i).(field).data;
end
  2 Comments
Jack Foley
Jack Foley on 24 Jul 2020
Thank you so much, that worked perfectly!
Bruno Silva
Bruno Silva on 6 Jan 2022
Thankk you! It helped me also :D

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!