通过Matlab中的struct进行Vectorize/Accelerate循环? [英] Vectorize/Accelerate looping through a struct of struct in Matlab?

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

问题描述

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

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

我有一个大小为1000的大型结构,里面的每个结构都是一个结构,也就是说,我有一个结构的结构.

I have a large struct of size 1000, each one inside is a struct, that is, I have a struct of struct.

每个 substruct 的样式相同,即字段相同.

Each substruct are in the same style, that is, the same fields.

我正在使用一个函数在每个 substruct

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 只是一个函数, mainStruct struct的结构 mainStruct(i)正在访问每个 subStruct .

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

我尝试过 structfun ,但它仅适用于struct的字段名称,不适用于struct的 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进行Vectorize/Accelerate循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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