skip a number after every two number in for loop

Hello,
I want to execute a for loop from value 1 to 10.
but within this range I want to skip number 3, 6 and 9. could you please help with the logic of skipping specific number at regular.

 Akzeptierte Antwort

madhan ravi
madhan ravi am 21 Jan. 2019
Bearbeitet: madhan ravi am 21 Jan. 2019
L=1:10;
for k = L(~ismember(L,3:3:L(end)))
k
end

4 Kommentare

yogi patel
yogi patel am 21 Jan. 2019
It works..?? thank you so much
John D'Errico
John D'Errico am 21 Jan. 2019
Bearbeitet: John D'Errico am 21 Jan. 2019
A related way with a little more elegance:
N = 10;
for k = setdiff(1:N,3:3:N)
k
end
Hmm. Or how about a while loop, with a variable step?
N = 10;
k = 0;
while k<N
k = k + 1 + (mod(k,3) == 2);
k
end
Or...
N = 10;
for k = sort([1:3:N, 2:3:N])
k
end
There are always a milion ways to solve any problem in MATLAB. :)
Thank you John D‘Errico I was about to post this as another possible solution.
yogi patel
yogi patel am 21 Jan. 2019
Thank you John for brief answer. Always good to know new ideas regarding simple tasks. :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by