matlab - 从结构字段创建全因子采样的巧妙方法
问题描述
我在 MATLAB 中有(例如)这个结构数组
g=struct();
g.var1=[0,1,2];
g.var2=[5,6,7];
g.var3={'a','b','c'};
...
我想创建一个单元格数组,对所有字段一一采样(网格网格)
想要一个单元阵列;
M×N 元胞数组
{[0]} {[5]} {'a'}
{[0]} {[5]} {'b'}
{[0]} {[5]} {'c'}
{[1]} {[5]} {'a'}
{[1]} {[5]} {'b'}
{[1]} {[5]} {'c'}
{[2]} {[5]} {'a'}
{[2]} {[5]} {'b'}
{[2]} {[5]} {'c'}
{[0]} {[6]} {'a'}
{[0]} {[6]} {'b'}
{[0]} {[6]} {'c'}
{[1]} {[6]} {'a'}
{[1]} {[6]} {'b'}
{[1]} {[6]} {'c'}
...
...
我希望我的代码适用于所有一般情况,例如只有一个字段或多个字段的输入结构。
对此进行编码的聪明方法是什么?
解决方案
您可以使用此问题的任何答案来获取数字向量的所有组合。我会将最佳答案定义为函数getIndices
,并使用输出索引对您的通用结构进行操作g
。
您必须进行的唯一额外处理是让数字数组和单元数组放置得很好,我只是添加了一个isnumeric
检查以进行相应的转换。
flds = fieldnames( g ); % get structure fields
% Get indices of fields (1:n for each field) and get combinations
idx = cellfun( @(fld) 1:numel(g.(fld)), flds, 'uni', 0 );
idx = getIndices( idx );
% Create output
out = cell(size(idx,1),numel(flds));
for ii = 1:numel(flds)
if isnumeric( g.(flds{ii}) )
out(:,ii) = num2cell( g.(flds{ii})(idx(:,ii)) );
else
out(:,ii) = g.(flds{ii})(idx(:,ii));
end
end
function combs = getIndices( vectors )
% Source: https://stackoverflow.com/a/21895344/3978545
n = numel(vectors); %// number of vectors
combs = cell(1,n); %// pre-define to generate comma-separated list
[combs{end:-1:1}] = ndgrid(vectors{end:-1:1}); %// the reverse order in these two
%// comma-separated lists is needed to produce the rows of the result matrix in
%// lexicographical order
combs = cat(n+1, combs{:}); %// concat the n n-dim arrays along dimension n+1
combs = reshape(combs,[],n); %// reshape to obtain desired matrix
end
推荐阅读
- c# - 无法在 C# 的 for 循环之外打印我的结果
- mule - APIkit API 控制台返回 json 示例而不是真实响应
- python - 数据框:在 if else 函数的新列中添加列出的值
- react-native - 一次向服务器发布多个参数 - React Native
- python-3.x - 在 Python 中计算 ICMP 回显请求的校验和
- apache - 在 apache 服务器上监控:为什么在 /var/log/monit 上监控日志“'apache' 错误 -- 未知资源 ID:[5]”
- javascript - IE 出现问题 delegate.iterator.return
- excel - 如何从本网站的下拉菜单中选择选项
- rdf - OWL rdfs:langString maxCardinality 每种语言
- powershell - dotnetcore/批处理脚本退出代码