Iterator for n-dimensional problems. Allows you to use a single for loop instead of nested loops

版本 1.4.0.0 (8.0 KB) 作者: Matt Caywood
Using an iterator, you can flatten complex arbitrarily nested loops to a simple single loop.
579.0 次下载
更新时间 2017/4/12

查看许可证

Ever have a simulation problem where the parameters being tested frequently change, but the computation stays the same? This iterator flattens complex and crazy-making nested loops into a single loop that iterates over all combinations of parameters.
As a result, it's very easy to change the iteration parameters without rewriting loops, reindenting code, updating indices, etc.
Sample nested loop code like this:

avalues = [1 2]; bvalues = [10 20]; cvalues = [100 200 300];
for ai = 1:length(avalues)
for bi = 1:length(bvalues)
for ci = 1:length(cvalues)
scoretable(ai,bi,ci) = avalues(ai) + bvalues(bi) + cvalues(ci);
end
end
end

Can be flattened into code like this, and any parameter can be added or removed by changing only paramvariables and paramvalues:

paramvariables = {'A' 'B' 'C'};
paramvalues = { {1 2} {10 20} {100 200 300}};
piter = paramiterator(paramvariables,paramvalues);
for i = 1:length(piter)
setvalues(piter,i);
scorelist(i) = A + B + C;
end
scoretable = listtotable(piter,scorelist);

Results can be easily displayed with displaytable (http://www.mathworks.com/matlabcentral/fileexchange/27920-displaytable).

Using the valuechanged setting, you can test whether a parameter has changed since the last iteration, before running some computation. This is like nesting the computation within only some of the loops, making paramiterator a full replacement for nested loops.

Now also supports iterating over multiple paired parameters simultaneously, for additional convenience and compatibility.

引用格式

Matt Caywood (2024). Iterator for n-dimensional problems. Allows you to use a single for loop instead of nested loops (https://www.mathworks.com/matlabcentral/fileexchange/28333-iterator-for-n-dimensional-problems-allows-you-to-use-a-single-for-loop-instead-of-nested-loops), MATLAB Central File Exchange. 检索来源 .

MATLAB 版本兼容性
创建方式 R2008a
兼容任何版本
平台兼容性
Windows macOS Linux
类别
Help CenterMATLAB Answers 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
版本 已发布 发行说明
1.4.0.0

fixed valuechanged bug, added reset function
improved description
updated description more

1.3.0.0

additional support for paired parameters

1.2.0.0

added parameter change testing

1.1.0.0

added example to description

1.0.0.0