Extracting every nth and (n+1)th element
14 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Inna Pelloso
el 6 de Dic. de 2020
Editada: Nenad Mijatovic
el 4 de Jun. de 2025
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
0 comentarios
Respuesta aceptada
Cris LaPierre
el 6 de Dic. de 2020
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)
Más respuestas (1)
Nenad Mijatovic
el 4 de Jun. de 2025
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 comentarios
Stephen23
el 4 de Jun. de 2025
Editada: Stephen23
el 4 de Jun. de 2025
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)
The simpler standard MATLAB approach (i.e. an even "more comact form") for returning every Nth element:
b = a(N:N:end)
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))
V = [0,1,2,6]; % => N, N+1, N+2, N+6
b = a(ismember(mod(1:numel(a),N),1+V))
See also:
Nenad Mijatovic
el 4 de Jun. de 2025
Editada: Nenad Mijatovic
el 4 de Jun. de 2025
of course. I actially missed the n+1 part of the orriginal question.
thanks for the correction.
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!