Meep
Meep

Reputation: 387

What is wrong with this for loop command in MATLAB (excluding an index)

I am trying to exclude an index within a for loop. I can't understand why the following code keeps bringing up an error:

for(l=1:Nmax, l~=m)

The error is

Error: File: BARW2Dwithducts.m Line: 76 Column: 24 Unbalanced or unexpected parenthesis or bracket.

I don't see how the expression is unbalanced (the code itself works fine and is error free if I just use for l=1:Nmax, but this doesn't give me what I need...

Upvotes: 0

Views: 56

Answers (2)

Zizy Archer
Zizy Archer

Reputation: 1390

To skip an index, your typical option is to put the following inside the loop (as the first thing):

if (l == m)
   continue
end

Another option is to generate all indices, then remove the target one:

allInds = 1:Nmax;
allInds(allInds == m) = []; % remove index m.
for l = allInds
...

This has a nice advantage that you can clearly see all the indices that will be visited before the loop even starts, and as you start adding extra conditions this one scales much better than a horrible nest of conditions inside the loop.

Upvotes: 3

Cris Luengo
Cris Luengo

Reputation: 60504

One way to skip the value m is to do as follows:

for l=[1:m-1,m+1:Nmax]
   % ...
end

Note that this will not work if m-1>Nmax, as you will visit values larger than Nmax.

Upvotes: 0

Related Questions