简体   繁体   中英

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

Yes. You can write:

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

Another solution:

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

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 (ie skip = [7, 18, 23] etc...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM