0

Example of my code: (Actual code is very long. Could be found in edit history)

X = {'a','b','c','d'}

for i = 1:length(X)
     if X(i) == 'a'    %// for example
          X(i)=[];
     end
end

Why didn't the counter stop at 3rd iteration? It tried to continue till 4th iteration and generated the following error :

Index exceeds matrix dimensions.

But as the first element 'a' was deleted, The actual size of array has become 3 (instead of 4). Shouldn't the 'looping' be stopped after the 3rd iteration?

3
  • I don't have matlab now, but i will check that tonight , interesting ... ;) Commented Jun 1, 2015 at 14:58
  • What is the length of region_L? Commented Jun 1, 2015 at 15:14
  • before the loop length(region_L)= 11 Commented Jun 1, 2015 at 15:21

5 Answers 5

3

You probably mean

X = ['a','b','c','d']

(with square brackets), so X is a char array (string), not a cell array


The problem is that within the loop you remove one entry of X, so X is left with 3 entries. Thus, when you try to access its 4th entry (at iteration i=4) you get an error.

This happens because the for exit condition is not re-evaluated at each iteration. At the for statement you say that i has to run from 1 to 4 (4 is the value of length(X) at that time), and that's what happens.

To achieve what you want you probably need a while loop. The while-loop condition is evaluated after each iteration, using the current values for the variables, to determine whether a new iteration should take place or not. So in the following code only 3 iterations occur, and you get no errors:

i = 1;
while i<=length(X)
    if X(i) == 'a'
        X(i) = [];
    else
        i = i + 1;
    end
end

The counter i should be incremented only if no element of X has been removed. Thanks to @matlabgui for the catch.

Sign up to request clarification or add additional context in comments.

3 Comments

@LuisMendo you need to add a continue after the X(i) = [] - consider the case where X = ['a' 'a' 'c' 'd']
@matlabgui Thanks! You are right, I didn't think about that. I've edited the answer. Now I increment the counter i only if no element has been removed. I think that's the same as continue but I find it clearer.
@LuisMendo - no problem! :) Yes counting on the else has the same desire - I have used both methods - depends on the bigger picture of your code!
1

I suspect your code is:

X={'a','b','c','d'}

for i = 1:length(X)
     if X{i} == 'a'    %for example
          X(i)=[]
     end
end

When X{i} == 'a' you are removing X(i) -> i.e. X becomes 3 long instead of 4. But you loop is programmed to go to the length of X before you started (i.e. 4).

In this type of situation you can do the loop in reverse:

X={'a','b','c','d'}

for i = length(X):-1:1
     if X{i} == 'a'    %for example
          X(i)=[]
     end
end

Another method is to store an inedx in the loop and then remove at the end:

X={'a','b','c','d'}

index = false(length(X),1);
for i = 1:length(X)
     if X{i} == 'a'    %for example
          index(i)= true;
     end
end
X(index) = [];

1 Comment

yes that's exactly the problem but I have to start my loop at the right direction : for i = 1 : length(X)
0

You will get error since Matlab's index of any array starts at 1, and you did the for-loop starting from 0.

Comments

0

MATLAB Arrays start with 1 and then you have to decrease the end of the loop because your vektor got smaller or get a second variable.

And I wasn't able to compare chars.. but with numbers it worked

so it would be

j=0
for i = 1:length(X)
     j=j+1;
     if X(j) == 'a'    %for example
          X(j)=[];
          j=j-1;
     end
end

Comments

0

I cannot recreate the problem, the code uses cells, and you cannot index the 0th cell. So I edited to code to look like this:

for i = 1:length(X)
     if X{i} == 'a'    %for example
      X{i}=[];
     end
end

>>X = 

[]    'b'    'c'    'd'

No problems detected

EDIT: based on your code, you are deleting the cells while running this loop; try deleting the value in your cell instead of deleting the cell,you want to use curly brackets {} instead of [], and if you want to delete the empty cells, simply do it at the end using:

X(~cellfun('isempty',X))  

2 Comments

You're right, but i have more complex code I have tryed to explain with simple code ( I will edit and put my code maybe you will see the problem ) thank you
@Devel I have edited my answer, please check if it makes any difference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.