What is wrong with this for loop command in MATLAB (excluding an index)
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
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...
for l=1:Nmax
Where did you see this syntax? You can’t just make up new syntax and expect it to work. Please read the MATLAB documentation page on the for loop. If the syntax is not described there, it’s not legal syntax.
– Cris Luengo
Jun 29 at 17:40
2 Answers
2
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.
One way to skip the value m
is to do as follows:
m
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
.
m-1>Nmax
Nmax
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
The error is trying to tell you your syntax is incorrect. To skip you would have to check the value inside the for loop with an if statement
– scrappedcola
Jun 29 at 17:32