Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: How to update struct fields "in place" using struct fun?

Tags:

matlab

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!

like image 604
Shai Avatar asked Dec 05 '12 08:12

Shai


1 Answers

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);
like image 149
Colin T Bowers Avatar answered Nov 15 '22 08:11

Colin T Bowers