Taking middle 4 values of n size array

33 ビュー (過去 30 日間)
James Morris
James Morris 2019 年 8 月 20 日
コメント済み: James Morris 2019 年 8 月 23 日
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 件のコメント
the cyclist
the cyclist 2019 年 8 月 20 日
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?

サインインしてコメントする。

採用された回答

Jon
Jon 2019 年 8 月 20 日
編集済み: Jon 2019 年 8 月 20 日
You could use something like, for an array A
n = length(A(:)) % : treats as column even if this is actually a multidimensional array
midpoint = round(n/2)
select = A(midpoint-1:midpoint+2); % slightly unsymmetrical 1 before, 2 after
Note, you may have to further clarify, what your really mean by "middle 4". There are two sources of asymmetry inherent in taking the "middle 4". If there are an even number of elements then the "middle" one is either closer to one end or the other. Also as you are taking an even number (4) elements then either they are offset one way or the other from the selected middle element
  4 件のコメント
Jon
Jon 2019 年 8 月 23 日
Are you still looking for more help with this?
James Morris
James Morris 2019 年 8 月 23 日
Sorry for the late reply. No I figured it out in the end. You guys are awesome, thank you.

サインインしてコメントする。

その他の回答 (2 件)

the cyclist
the cyclist 2019 年 8 月 20 日
編集済み: the cyclist 2019 年 8 月 20 日
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
the cyclist 2019 年 8 月 20 日
編集済み: the cyclist 2019 年 8 月 20 日
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.

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by