Vectorize/Accelerate looping through a struct of s

2019-09-08 08:44发布

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?

1条回答
老娘就宠你
2楼-- · 2019-09-08 09:02

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 use arrayfun which allows you to write it in one line, but it is slower.

result=arrayfun(@(x)myfunction(x.field(1:1000)),mainStruct)

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.

查看更多
登录 后发表回答