フィルターのクリア

global variable in for loop

2 ビュー (過去 30 日間)
Linford Briant
Linford Briant 2012 年 1 月 18 日
Hi,
I have a for loop, which has last iterative defined as the size of some matrix K, i.e.
[a,b]=size(K)
for i=1:a
CODE
end
Trouble is, the "CODE" in the for loop redefines how large K is - in particular, it decreases a. This means that the for loop experiences an "Index exceeds matrix dimensions." error. How does one go about fixing this? I thought that in the for loop I could have:
a=a-1;
everytime the "CODE" decreases the size of K, but it don't work none!
Thanks,
Linford

採用された回答

Walter Roberson
Walter Roberson 2012 年 1 月 18 日
If you are deleting the entry you are examining under some circumstances, then the easiest change is often to run the loop backwards .

その他の回答 (1 件)

Jan
Jan 2012 年 1 月 18 日
The argument of the FOR loop is calculated once and is not influenced by the contents of the loop - in opposite to C.
You can check the exceeding index explicitely:
[a,b] = size(K);
for i = 1:a
if i > size(K, 1)
break;
end
CODE
end
Using a WHILE loop is a nice alternative:
[a,b] = size(K);
while i <= size(K, 1)
CODE
i = i + 1;
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by