1

I have a huge dynamic structure. It looks something like this:

s.one.name = 'Mr. Doe';
s.one.time = '12:00';
s.one.ID = '209';
s.one.data = 'Data1';

s.two.name = 'Ms. Jane';
s.two.time = '13:00';
s.two.ID = '210';
s.two.data = 'Data2';

s.three.name = 'Ms. Alice';
s.three.time = '14:00';
s.three.ID = '212';
s.three.data = 'Data3';

s.four.name = 'Mr. Smith';
s.four.time = '14:00';
s.four.ID = '212';
s.four.data = 'Data4';

Now, I want to access and store only the first two fields one and two (out of all the given fields) and its corresponding data into a new dynamic structure snew.

I have tried doing the following things:

for ii = 1:2
    snew = [s.(ii)];
end

Error: Argument to dynamic structure reference must evaluate to a valid field name.

Could anyone help me out in acheiving this task?

Thank you in advance

Suever
  • 64,497
  • 14
  • 82
  • 101
Nick
  • 55
  • 8
  • The notation `s.(ii)` implies that `ii` is a character vector containing the *name* of the field you want to access, which is why your code generates the error shown. If you just access `s.one` or `s.two` you will get a struct containing the four fields from `s.one` or `s.two` respectively. It's not clear to me exactly what you want `snew` to contain though - can you show us? – nekomatic Dec 05 '16 at 10:42

3 Answers3

0

You want a vector of structs:

s(1) = struct()
s(1).name = 'Mr. Doe'

...

s(2) = struct()
s(2).name = 'Ms. Jane'
...

then you can access the vector of structs using indexing:

snew = s(i)

if you want only the first two members you can do:

snew = s(1:2)
gauteh
  • 16,435
  • 4
  • 30
  • 34
  • You're suggesting that the questioner changes how they are storing the data in the first place, which may be a good idea if they can do so, but in the example data shown above, `s` has only one member and it seems they want to access all the fields in `s.one` and `s.two` respectively. – nekomatic Dec 05 '16 at 10:44
  • @nekomatic Yes - it seems more likely that restructuring in a way as I have suggested is a better approach than sticking with the original storage method. – gauteh Dec 05 '16 at 12:38
0

For two fields you can do it stright forward:

snew = struct('one', s.one, 'two', s.two);

for variable number of fields (say k) you can do it as following:

names = fieldnames(s);
vals = struct2cell(s);
list = [names(1:k) vals(1:k)]';
snew = struct(list{:});
0

You can put the fields you want to copy in a cell array and then loop through that and access struct fields via dynamic field names.

to_keep = {'one', 'two'};

out = struct();

for k = 1:numel(to_keep)
    out.(to_keep{k}) = s.(to_keep{k});
end

As others have noted, there is probably a better way to organize your data to make this operation simpler.

Suever
  • 64,497
  • 14
  • 82
  • 101