I am looking for something similar to sapply function in R in Matlab. I have the current issue:
I have a large struct of size 1000, each one inside is a struct, that is, I have a struct of struct.
Each substruct are in the same style, that is, the same fields.
I am using a function to do something on each substruct
The code looks like:
for i =1:length(mainStruct)
disp(i);
result(i) = myfunction(mainStruct(i).field(1:1000));
end
In the above, myfunction is just a function, mainStruct is the sturct of struct, mainStruct(i) is accessing each subStruct.
I have tried structfun, but it only works on struct's field names, not on struct of struct.
The question is how I can get rid of this loop?
Having a function
myfunction
which requires to be called for each vector individually, you can not vectorize the loop. You can only iterate. You could usearrayfun
which allows you to write it in one line, but it is slower.For loops in MATLAB are typically (one of) the fastest possibility to iterate. Only avoid them when iteration is not required. In this case, with
myfunction
not being vectorized, you need iteration.