Abdulmalik Morghem
Abdulmalik Morghem

Reputation: 127

How to assign range of integers in for loop using matlab and exclude a number in that range?

I would like to have a for loop with 1:25 range but I do not want the for loop to go through number 23 in that range

in another format; I want it like this 1:22 24:25 is it doable this way?

please help

Upvotes: 0

Views: 187

Answers (3)

Dan
Dan

Reputation: 45762

Just to add an alternative:

skip = [23];
for idx = 1:25
   if ~any(idx == skip)
       %// Your code here
   end
end

I think it's more readable than using [1:22 24:25] as your loop variable as you can see clearly and quickly which numbers are being skipped (unless [1:22 24:25] is a variable getting generated elsewhere in which case I would go with that method), it avoids continue which is controversial and it's easy to add other numbers to skip (i.e. skip = [7, 18, 23] etc...)

Upvotes: 2

tashuhka
tashuhka

Reputation: 5126

Another solution:

for idx=1:25
    if idx==23, continue, end
    disp(num2str(idx));
end

Upvotes: 2

Max
Max

Reputation: 2131

Yes. You can write:

for num = [1:22 24:25]
    % do something with num
end

Upvotes: 6

Related Questions