Extracting every nth and (n+1)th element

조회 수: 19 (최근 30일)
Inna Pelloso
Inna Pelloso 2020년 12월 6일
편집: Nenad Mijatovic 2025년 6월 4일
Hi,
I have A = (1:101). How can I extract every nth and (n+1)th element?
For example, if n = 10, I want reate B = [10, 11, 20, 21, ...100, 101].
I know how to extract every nth element using: A(1:n:end).
Any help would be appreciated! Thank you.
Inna

채택된 답변

Cris LaPierre
Cris LaPierre 2020년 12월 6일
I'm not aware of any slick way to do this. I'd combine two arrays, one from 10:10:101, and one from 11:10:101.
n=10;
A = (1:101);
ind = sort([n:n:101 n+1:n:101]);
A(ind)
ans = 1×20
10 11 20 21 30 31 40 41 50 51 60 61 70 71 80 81 90 91 100 101

추가 답변 (1개)

Nenad Mijatovic
Nenad Mijatovic 2025년 6월 4일
Not sure dose this do better then already offered answers but this might be more comact form:
a = [1:1000]; % array
N = 10; % nth element
b = a(mod(1:length(a),N)==0); %resulting array
I have been using this trick to preview large datasets.
  댓글 수: 2
Stephen23
Stephen23 2025년 6월 4일
편집: Stephen23 2025년 6월 4일
The answer does not solve the original question (which requires not only the Nth but also the (N+1)th elements), as it returns only every Nth element:
a = 1:1000; % removed superfluous square brackets
N = 10;
b = a(mod(1:length(a),N)==0)
b = 1×100
10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200 210 220 230 240 250 260 270 280 290 300
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
The simpler standard MATLAB approach (i.e. an even "more comact form") for returning every Nth element:
b = a(N:N:end)
b = 1×100
10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200 210 220 230 240 250 260 270 280 290 300
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
However this answer could be modified to solve a slightly generalized version of the original question:
V = [0,1]; % => N, N+1
b = a(ismember(mod(1:numel(a),N),1+V))
b = 1×200
1 2 11 12 21 22 31 32 41 42 51 52 61 62 71 72 81 82 91 92 101 102 111 112 121 122 131 132 141 142
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
V = [0,1,2,6]; % => N, N+1, N+2, N+6
b = a(ismember(mod(1:numel(a),N),1+V))
b = 1×400
1 2 3 7 11 12 13 17 21 22 23 27 31 32 33 37 41 42 43 47 51 52 53 57 61 62 63 67 71 72
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
See also:
Nenad Mijatovic
Nenad Mijatovic 2025년 6월 4일
편집: Nenad Mijatovic 2025년 6월 4일
of course. I actially missed the n+1 part of the orriginal question.
thanks for the correction.

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by