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

I have a structure

sa = [1 2 3]; sb = [2 3 4 5]; sc = [9, 6 ,3]; sd = ... % etc. - you got the gist of it 

Now I want to apply a function / operation to the data stored in each field and change the contents of the field, i.e. I want to apply

 sa = myFun( sa ); sb = myFun( sb ); sc = myFun( sc ); % etc. ... 

How can I do this without explicitly writing all the fields as above? I was thinking about structfun - but I'm not sure how to make this modification in place ...

Thanks!

+6
source share
1 answer

For an eager reader, the structfun solution is at the bottom of my answer :-) But I will ask myself first ...

What is wrong with using a loop? The following example shows how to do this:

 %# An example structure Sa = 2; Sb = 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 like arrayfun and cellfun are usually slower than an explicit loop . I assume that structfun is probably suffering from the same problem, so why bother?

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

 %# structfun solution Sa = [2 4]; Sb = 3; MyFunc = @(x) (x.^2); S = structfun(MyFunc, S, 'UniformOutput', 0); 
+7
source

All Articles