Matlab: Assigning same value to (different) fields in the same position of a struct array -
suppose have 1x10 struct my_struct 2 fields: fielda , fieldb.
how should assign scalar number (or other entity) on specific position fields in more direct form?
in other words, there way this:
my_struct(5).fielda = pi; my_struct(5).fieldb = pi; in way this: my_struct(5).* = pi or my_struct(5) = deal(pi)?
you can use combination of fieldnames , cell2struct programmatically build struct same value in fields, , full-struct assignment.
function out = setallfields(s, value) %setallfields build scalar struct template, replacing field values % s template struct, , value value desired in fields out = cell2struct(repmat({value}, [numel(fieldnames(s)) 1]), fieldnames(s)); with function defined, can assignment this, using single or multiple target indexes.
my_struct(5) = setallfields(my_struct, pi); my_struct([2 4:6]) = setallfields(my_struct, 'foo');
Comments
Post a Comment