필터 지우기
필터 지우기

Colon syntax for creating a sequence of numbers that skips a given number?

조회 수: 8 (최근 30일)
Thomas Hyatt
Thomas Hyatt 2023년 3월 18일
댓글: John D'Errico 2023년 3월 19일
I may be going crazy, but I remember both reading about and using a part of colon notation for creating a sequence of numbers (say 1:10 giving 1 2 3 4 5 6 7 8 9 10) but skipping a given number.
For instance, if I wanted 1:10 but to skip the number 5, it would yield 1 2 3 4 6 7 8 9 10.
I thought it was something like 1:~5:10, but that is certainly not the notation.
I know that
number = 5;
sequnce = [1:number-1 number+1:10];
would yield the same thing, but I distinctly remember a cleaner notation for it. I have been entirely unsuccessful in finding anything about it online. Does it actually exist, or is my memory making things up?

답변 (1개)

John D'Errico
John D'Errico 2023년 3월 18일
편집: John D'Errico 2023년 3월 18일
You can't, at least not directly. But it is quite simple. For example:
setdiff(1:10,3) % 1:10, missing 3
ans = 1×9
1 2 4 5 6 7 8 9 10
There are probably other solutions too, as there always are, but I prefer this one. It is easy to understand, and easy to write.
The notation you remember is not anything in MATLAB, at least not currently. It may have been something in another language you recall.
  댓글 수: 2
Walter Roberson
Walter Roberson 2023년 3월 19일
Note that you may have to use the 'stable' option of setdiff.
setdiff(10:-1:1,3)
ans = 1×9
1 2 4 5 6 7 8 9 10
setdiff(10:-1:1,3,'stable')
ans = 1×9
10 9 8 7 6 5 4 2 1
John D'Errico
John D'Errico 2023년 3월 19일
Good point about the 'stable' option, necessary if you want to leave the order unchanged in a decreasing sequence.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by