Clear Filters
Clear Filters

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

4 views (last 30 days)
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.

Answers (1)

Shubham
Shubham on 19 Oct 2023
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!