Bant
Bant

Reputation: 73

Iterate through a lot of Structs

my Problem is the following:

I have about 300 Struct files given. They are set up like this:

DSC_0001 has about 250 other struct files in it: -> like this: DSC_0001.marker_1 And this one has 10 Numbers in it. Like that: DSC_0001.marker_1.flow_angle = 90

and now I want to iterate through all the Struct files Something like that:

for i = 1:300
    for j = 1:250
         flow_angle = DSC_**i**.marker_**j**
    end
end

Is there a way to do this? I have the feeling that it could be really easy but I just can't find the solution... I hope my question is clear enough...

Thanks for your help!

Upvotes: 1

Views: 95

Answers (2)

ioums
ioums

Reputation: 1395

If possible don't use eval.

It depends on how your data is stored, but one possiblity is that it is in a .mat file. In that case it can be loaded using

DSC_structs = load('My_DSC_struct_file.mat');

and then you can access the values like so:

for i = 1:300
    for j = 1:250
        flow_angle(i,j) = DSC_structs.(['DSC_' sprintf('%04d',i)]).(['marker_' sprintf('%d',j)]);
    end
end

Why avoid the eval function

Edit: You say that each struct is in a different file. That's a bit messier. I would probably do something like this to load them:

DSC_structs = cell(1,300);
for i = 1:300
    %Note: I'm guess at your file names here
    DSC_structs{i} = load(['DSC_' sprintf('%04d',i) '.mat'];
end

and then access the values as

DSC_structs{i}.(['DSC_' sprintf('%04d',i)]).(['marker_' sprintf('%d',j)]);

Upvotes: 2

Dan
Dan

Reputation: 45741

I guess this is a use case for the dreaded eval function:

for i = 1:300
    for j = 1:250
         eval (['flow_angle = DSC_', sprintf('%04d',i), '.marker_', num2str(j)]);
    end
end

BUT NB there are 2 problems with my code above

  1. You haven't told us where you want to store your angle, so my code doesn't :/ but you'd want something like this if you just want to store them in a matrix: eval (['flow_angle(', num2str(i), ',', num2str(j), ') = DSC_', sprintf('%04d',i), '.marker_', num2str(j)])
  2. eval is a horrible way of doing things but you're forced to because someone saved your data in a horrible. Sort yourself out now for the future by re-saving your data in a smarter way! so something like:

.

for i = 1:300
     eval ( ['DSC(', num2str(i), ') = DSC_', sprintf('%04d',i)]);
end
%// then save DCS!

And now your can iterate through this matrix of structs rather than having a 300 structs polluting your workspace and forcing you to use eval

Upvotes: 0

Related Questions