matlab-struct

Iterating through struct fieldnames in MATLAB

南楼画角 提交于 2019-11-27 06:24:24
My question is easily summarized as: "Why does the following not work?" teststruct = struct('a',3,'b',5,'c',9) fields = fieldnames(teststruct) for i=1:numel(fields) fields(i) teststruct.(fields(i)) end output: ans = 'a' ??? Argument to dynamic structure reference must evaluate to a valid field name. Especially since teststruct.('a') does work. And fields(i) prints out ans = 'a' . I can't get my head around it. You have to use curly braces ( {} ) to access fields , since the fieldnames function returns a cell array of strings: for i = 1:numel(fields) teststruct.(fields{i}) end Using parentheses

How do I access structure fields dynamically?

痴心易碎 提交于 2019-11-26 18:39:28
I have a structure with many fields which are vectors of different lengths. I would like to access the fields within a loop, in order. I tried getfield as follows but MATLAB doesn't like that. How can I do this? S = struct('A', [1 2], 'B',[3 4 5]); SNames = fieldnames(S); for loopIndex = 1:2 field = getfield(S, SNames(loopIndex)); %do stuff w/ field end ??? Index exceeds matrix dimensions I'm using structures in the first place because an array would have trouble with the different field lengths. Is there a better alternative to that? Try dynamic field reference where you put a string in the

Iterating through struct fieldnames in MATLAB

混江龙づ霸主 提交于 2019-11-26 11:59:38
问题 My question is easily summarized as: \"Why does the following not work?\" teststruct = struct(\'a\',3,\'b\',5,\'c\',9) fields = fieldnames(teststruct) for i=1:numel(fields) fields(i) teststruct.(fields(i)) end output: ans = \'a\' ??? Argument to dynamic structure reference must evaluate to a valid field name. Especially since teststruct.(\'a\') does work. And fields(i) prints out ans = \'a\' . I can\'t get my head around it. 回答1: You have to use curly braces ( {} ) to access fields , since

How do I access structure fields dynamically?

偶尔善良 提交于 2019-11-26 06:29:25
问题 I have a structure with many fields which are vectors of different lengths. I would like to access the fields within a loop, in order. I tried getfield as follows but MATLAB doesn\'t like that. How can I do this? S = struct(\'A\', [1 2], \'B\',[3 4 5]); SNames = fieldnames(S); for loopIndex = 1:2 field = getfield(S, SNames(loopIndex)); %do stuff w/ field end ??? Index exceeds matrix dimensions I\'m using structures in the first place because an array would have trouble with the different