필터 지우기
필터 지우기

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

조회 수: 4 (최근 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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by