向量化/加速循环通过 Matlab 中的 struct 结构? [英] Vectorize/Accelerate looping through a struct of struct in Matlab?

查看:25
本文介绍了向量化/加速循环通过 Matlab 中的 struct 结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Matlab 的 R 中寻找类似于 sapply 函数 的东西.我有当前的问题:

I am looking for something similar to sapply function in R in Matlab. I have the current issue:

我有一个1000大小的大struct,里面每个都是一个struct,也就是我有一个struct的struct.

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

代码如下:

 for i =1:length(mainStruct)
      disp(i);
      result(i) = myfunction(mainStruct(i).field(1:1000));
 end

上面的myfunction只是一个函数,ma​​inStructstruct的结构ma​​inStruct(i) 正在访问每个 subStruct.

In the above, myfunction is just a function, mainStruct is the sturct of struct, mainStruct(i) is accessing each subStruct.

我尝试过 structfun,但它只适用于结构的字段名称,而不适用于结构的 struct.

I have tried structfun, but it only works on struct's field names, not on struct of struct.

问题是我怎样才能摆脱这个循环?

推荐答案

有一个函数 myfunction 需要为每个向量单独调用,你不能向量化循环.你只能迭代.您可以使用 arrayfun ,它允许您在一行中编写它,但速度较慢.

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)

MATLAB 中的 For 循环通常是(之一)迭代最快的可能性.只有在不需要迭代时才避免它们.在这种情况下,myfunction 没有被向量化,你需要迭代.

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.

这篇关于向量化/加速循环通过 Matlab 中的 struct 结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆