6

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!

Shai
  • 111,146
  • 38
  • 238
  • 371

1 Answers1

7

For the impatient reader, the structfun solution 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:

%# An example structure
S.a = 2;
S.b = 3;

%# An example function
MyFunc = @(x) (x^2);

%# Retrieve the structure field names
Names = fieldnames(S);

%# Loop over the field-names and apply the function to each field
for n = 1:length(Names)
    S.(Names{n}) = MyFunc(S.(Names{n}));
end

Matlab functions such as arrayfun and cellfun typically are slower than an explicit loop. I'm guessing structfun probably suffers from the same problem, so why bother?

However, if you insist on using structfun it can be done as follows (I made the example a little more complicated just to emphasize the generality):

%# structfun solution
S.a = [2 4];
S.b = 3;
MyFunc = @(x) (x.^2);
S = structfun(MyFunc, S, 'UniformOutput', 0);
Community
  • 1
  • 1
Colin T Bowers
  • 18,106
  • 8
  • 61
  • 89
  • Very interesting point regarding the runtime of `cellfun` and `arrayfun`. I am still more inclined toward `structfun` because I feel it is more "elegant" than loop. I also think it contributes to the readability of the code. Thanks for your suggestion! – Shai Dec 05 '12 at 08:58
  • 1
    @Shai Fair enough. I've updated my answer to include a `structfun` solution. If you think I've answered the question, then feel free to click the tick mark. Otherwise, let me know and perhaps I can improve it. Cheers :-) – Colin T Bowers Dec 05 '12 at 09:04