[英]A conditional statement during a for loop in MATLAB
這是我嘗試一個簡單的例子(看起來毫無意義),但這個想法比這個簡單的代碼更大。
在 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)
理想情況下,我想要一個不包含8
的1000
長的數字列表。
如果您想要做的是循環的 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
不。
使用 for 循環,循環數是在循環開始時確定的,它不是動態的。
為了做你想做的事,你需要使用一個while循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.