MATLAB:将结构字段名称的一部分传递给函数

标签 matlab function struct

我需要将结构名称的一部分传递给函数。

可用结构的示例:

systems.system1.stats.equityCurve.relative.exFee
systems.system1.stats.equityCurve.relative.inFee
systems.system2.stats.equityCurve.relative.exFee
systems.system2.stats.equityCurve.relative.inFee
systems.system1.returns.aggregated.exFee
systems.system1.returns.aggregated.inFee
systems.system2.returns.aggregated.exFee
systems.system2.returns.aggregated.inFee
... This goes on...

在一个函数中,我按如下方式遍历结构:

function mat = test(fNames)

feeString = {'exFee', 'inFee'};
sysNames = {'system1', 'system2'};

for n = 1 : 2
    mat{n} = systems.(sysNames{n}).stats.equityCurve.relative.(feeString{n});
end

end

我喜欢在循环中以灵活的方式处理中间部分,即 systems.(sysNames{n}) 之后和 .(feeString{n} )(比较示例)。

我现在正在寻找一种方法将中间部分作为输入参数 fNames 传递给函数。循环应该包含类似的东西

mat{n} = systems.(sysNames{n}).(fName).(feeString{n});

最佳答案

如何使用辅助函数,例如

function rec_stru = recSA(stru, field_names)
if numel(field_names) == 1
    rec_stru = stru.(field_names{1});
else
    rec_stru = recSA(stru.(field_names{1}), field_names(2:end));
end

此函数将中间字段名称作为元胞数组。 这将变成这个声明:

mat{n} = systems.(sysNames{n}).stats.equityCurve.relative.(feeString{n});

进入

mat{n} = recSA(systems.(sysNames{n}), {'stats', 'equityCurve', 'relative', feeString{n}});

然后可以将元胞数组的第一部分作为参数传递给函数。

关于MATLAB:将结构字段名称的一部分传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46851549/

相关文章:

matlab - mat2gray对multithresh的影响

c - 在 "C"头文件中声明的静态函数

objective-c - 为什么 LLDB 使用我的结构的错误字段进行算术运算?

matlab - 设置多个控件的多个属性

Matlab 查询 : How to align 'title' at the botton of the figure when plotting points

matlab - 在matlab中找到图像的逆对数变换

r - 这个优化算法会使用哪种方法?

python - 是否可以使用 python 中的函数清空字符串?

c - 在客户端之前运行多进程服务器

c - 在 C 中为结构类型分配内存