matlab - MATLAB 中 for 循环期间的条件语句
问题描述
这是我尝试一个简单的例子(看起来毫无意义),但这个想法比这个简单的代码更大。
在 for 循环期间,如果发生某些事情,我想跳过 for 循环的这一步,然后在最后添加一个额外的步骤。
我正在尝试创建一个不包括数字 8 的数字列表。
如果代码创建一个 8,这将意味着 exitflag 等于 1。
我可以调整这个程序,以便如果
exitflag=1
, 它将删除该结果并添加另一个循环。
编码:
for i = 1:1000
j = 1+round(rand*10)
if j == 8
exitflag = 1
else
exitflag = 0
end
storeexit(i)=exitflag;
storej(i)=j;
end
sum(storeexit)
理想情况下,我想要一个1000
不包含8
.
解决方案
如果您想要做的是循环的 1000 次迭代,但如果您不喜欢它的结果,则重复for
循环迭代,而不是在末尾标记重复,您可以做的是在循环内循环,直到您喜欢该迭代的结果:
stores = zeros(1000,1); % Note that it is important to preallocate arrays, even in toy examples :)
for i = 1:1000
success = false; % MATLAB has no do..while loop, this is slightly more awkward....
while ~success
j = 1+round(rand*10);
success = j ~= 8;
end
storej(i) = j; % j guaranteed to not be 8
end
推荐阅读
- linux - 如何在不使用“write”命令的情况下获得可执行文件的输出?
- ckeditor - 内容安全策略编辑器
- javascript - CSS 继承之前的背景 rgba 值 EXCEPT alpha(不透明度)
- json - 用 jq(或 python3)解析 Maxmind JSON?
- vb.net - 如何将声明的变量添加到文本框中?
- reactjs - 全球安装的 ReactJs 库
- flutter - 如何使 RaisedButton 在颤动中自动适应屏幕宽度
- javascript - 从 React 到 Vue,如何使用 .map 方法循环遍历数组?
- python - 在激活 conda 环境时收到一些消息
- python - 在 PyCharm 中找不到 webdriver_manager 模块