Taking middle 4 values of n size array
Afficher commentaires plus anciens
I know how to take the first 4 values of an n size array (1:4)
and the last 4 (end-4:end)
but how would I take the middle 4 values of an n size array no matter the length?
Thanks
1 commentaire
the cyclist
le 20 Août 2019
Do you know if the number of array elements is always even, or always odd? How do you want to define the middle if there are an odd number?
Réponse acceptée
Plus de réponses (2)
the cyclist
le 20 Août 2019
Modifié(e) : the cyclist
le 20 Août 2019
Here is one way, assuming the number of elements is even:
% Input
a = rand(1,8);
numberElements = numel(a);
numberToRemove = numberElements - 4;
numberToRemoveFromEachEnd = numberToRemove/2;
output = a(numberToRemoveFromEachEnd+1:end-numberToRemoveFromEachEnd)
the cyclist
le 20 Août 2019
Modifié(e) : the cyclist
le 20 Août 2019
Here is one way, which will work for either even- or odd-length arrays. It is not efficient.
% Input
a = rand(1,9);
whichEnd = 1;
while numel(a) > 4;
a = a(whichEnd:(end+whichEnd-2))
whichEnd = 3-whichEnd;
end
end
It will choose the "slightly left of center" for odd-length array.
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!