1

I have a matlab structure array Modles1 of size (1x180) that has fields a, b, c, ..., z.

I want to understand how many distinct values there are in each of the fields. i.e.

max(grp2idx([foo(:).a]))

The above works if the field a is a double. {foo(:).a} needs to be used in the case where the field a is a string/char.

Here's my current code for doing this. I hate having to use the eval, and what is essentially a switch statement. Is there a better way?

names = fieldnames(Models1);
for ix = 1 : numel(names)
    className = eval(['class(Models1(1).',names{ix},')']);
    if strcmp('double', className) || strcmp('logical',className)
        eval([' values = [Models1(:).',names{ix},'];']);
    elseif strcmp('char', className)
        eval([' values = {Models1(:).',names{ix},'};']);
    else
        disp(['Unrecognized class: ', className]);
    end
    % this line requires the statistics toolbox.
    [g, gn, gl] = grp2idx(values);
    fprintf('%30s : %4d\n',names{ix},max(g));
end
2
  • The use of eval is indeed best minimized, but a switch is not bad practice. If you want it to look nicer you can use the actual switch case syntax. Commented Nov 9, 2012 at 21:47
  • @Dennis It isn't a switch as such that I was not liking, it was that I had to switch to handle different class types. That strikes me as just ugly. Commented Nov 9, 2012 at 22:52

1 Answer 1

5

Indeed, there is a better way. Surprisingly, MATLAB allows you to access the struct fields using a key string without eval, for instance:

Models1(1).(names{ix})

so instead, you can write this:

className = class(Models1(1).(names{ix});
...
values = [Models1(:).(names{ix})];
...
values = {Models1(:).(names{ix})};

Also, instead of using class and strcmp, you can just test the same conditions with isa:

v1 = Models1(1).(names{ix});
if (isa(v1, 'double') || isa(v1, 'logical'))
    values = [Models1(:).(names{ix})];
    % # ...
elseif (isa(v1, 'char'))
    values = {Models1(:).(names{ix})};
    % # ...
else
    disp(['Unrecognized class: ', class(v1)]);
end

It should be much faster.

Sign up to request clarification or add additional context in comments.

1 Comment

I am very surprised I didn't see that in the documentation. Sweet!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.