Better code for accessing fields in a matlab structure array?

Posted by John on Stack Overflow See other posts from Stack Overflow or by John
Published on 2012-11-09T20:47:04Z Indexed on 2012/11/09 23:00 UTC
Read the original article Hit count: 196

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about matlab

Related posts about reflection