For loop going beyond my stated limit, did I find a glitch?

6 ビュー (過去 30 日間)
John Ruf
John Ruf 2020 年 10 月 21 日
回答済み: Shubham 2023 年 10 月 19 日
Hi so I have the following for loop that I'm using to create an approximation of the cantor set.
x=0.5;
n=5;
a = cell(1,n);
a{1}=[0,1];
count=1;
for i = 2:n
a{i} = linspace(0, 1, 3^(i-1)+1);
clear j;
for j=1:(length(a{i})-1)
if a{i}(j)>1/3
if a{i}(j)<2/3
a{i}(j)=[];
else
count=1+count;
end
else
count=1+count;
end
end
end
However, matlab keeps pushing j past its normal limits and frankly I have no idea why. For example when i is 4, it'll stop at j=25, but that's impossible, because j has to stop after 23 if you just run the length when i is 4.

回答 (1 件)

Shubham
Shubham 2023 年 10 月 19 日
The issue you're experiencing with the loop is caused by modifying the size of the array a{i} within the loop. When you remove elements from a{i} using a{i}(j) = [], the loop counter j becomes out of sync with the updated size of a{i}.
To fix this issue, you can iterate the loop in reverse order, starting from the last index and moving towards the first index. This way, removing elements won't affect the subsequent iterations. Here's the modified code:
x = 0.5;
n = 5;
a = cell(1, n);
a{1} = [0, 1];
count = 1;
for i = 2:n
a{i} = linspace(0, 1, 3^(i-1) + 1);
for j = length(a{i}):-1:2
if a{i}(j) > 1/3 && a{i}(j) < 2/3
a{i}(j) = [];
else
count = count + 1;
end
end
end
Hope this helps.

カテゴリ

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