有没有更优雅的方式来编写这些循环? [英] Is there a more elegant way to write these loops?
问题描述
我有一个脚本,需要少量的参数运行。我有兴趣探索结果作为参数改变,所以我定义了一些 scan
数组在顶部,包装整个代码在多个 loops
并将参数值设置为当前扫描值。
I have a script that requires a handful of parameters to run. I'm interested in exploring the results as the parameters change, so I define a few scan
arrays at the top, wrap the whole code in multiple for loops
and set the parameters values to the current scan values.
这是容易出错和不雅的。更改代码的过程是:1)重置扫描
顶部的变量,2)注释例如 b = scan2(j2)
和3)取消注释 b = b0
。
This is error prone and inelegant. The process for changing the code is: 1) reset scan
variables at the top, 2) comment out eg b = scan2(j2)
and 3) uncomment b=b0
.
什么是更好的方法,允许变量设置为数组,然后运行所有这样的组合的代码? :
close all
clear all
%scan1 = linspace(1,4,10);
scan1 = 0;
scan2 = linspace(0,1,10);
scan3 = linspace(-1,0,10);
for j3 = 1:length(scan3)
for j2 = 1:length(scan2)
for j1 = 1:length(scan1)
a = a0;
%b = scan2(j2);
b = b0;
%c = c0;
c = scan3(j3);
d = scan2(j2);
%(CODE BLOCK THAT DEPENDS ON variables a,b,c,d...)
end
end
end
推荐答案
基于这个想法使用一个for循环来模拟多个循环,我试着适应你的情况。在实现良好的内存效率和可用性的同时,此解决方案比使用个别循环更慢。
Based on this idea to use one for loop to simulate multiple loops, I tried to adapt it to your case. While fulfilling a good memory efficiency and usability, this solution is slower than using individual for loops.
%define your parameters
p.a = 1;
p.b = linspace(1,4,4);
p.c = linspace(11,15,5);
p.d = linspace(101,104,4);
p.e = 5;
iterations=structfun(@numel,p);
iterator=cell(1,numel(iterations));
for jx = 1:prod(iterations)
[iterator{:}]=ind2sub(iterations(:).',jx);%.'
%This line uses itertor to extract the corresponding elemets of p and creates a struct which only contains scalars.
q=cell2struct(cellfun(@(a,b)(a(b)),struct2cell(p),iterator(:),'uniform',false),fieldnames(p));
%__ (CODE THAT DEPENDS ON q.a to q.e here) __
end
对于我测试的场景,它增加了 0.0002
每次迭代的计算开销, 0.0002。* prod(iterations) code>总计
For the scenarios I tested it adds an computation overhead below 0.0002
s per iteration which is 0.0002.*prod(iterations)
s in total.
这篇关于有没有更优雅的方式来编写这些循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!