I have a structure
s.a = [1 2 3];
s.b = [2 3 4 5];
s.c = [9, 6 ,3];
s.d = ... % etc. - you got the gist of it
Now I want to apply a function/operation on the data stored in each field and modify the content of the field, that is I want to apply
s.a = myFun( s.a );
s.b = myFun( s.b );
s.c = myFun( s.c ); % etc. ...
How can I do it without explicitly write all the fields as above?
I was thinking of structfun – but I’m not so sure how to accomplish this “in place” modification…
Thanks!
For the impatient reader, the
structfunsolution is at the bottom of my answer 🙂 But I would first ask myself…What’s wrong with using a loop? The following example shows how it can be done:
Matlab functions such as
arrayfunandcellfuntypically are slower than an explicit loop. I’m guessingstructfunprobably suffers from the same problem, so why bother?However, if you insist on using
structfunit can be done as follows (I made the example a little more complicated just to emphasize the generality):