How to take the X smaller values of an array ?

1 回表示 (過去 30 日間)
Hidir ABAY
Hidir ABAY 2016 年 7 月 27 日
回答済み: Paxorus Sahay 2016 年 7 月 27 日
Hello everyone,
I have an array x (for example size(x)= 1, 10) and x=(1, 4, 100, 3, 14, 56, 8, 90, 23, 2).
My question is how can I keep the 6 smaller values of x without making a sort ? Because when I do a sort, it changes the place of the values.
For example if y is the output array I want that y=(1, 4, 3, 14, 8, 2)
Thanks for reading.

採用された回答

Adam
Adam 2016 年 7 月 27 日
編集済み: Adam 2016 年 7 月 27 日
[y,idx] = sort( x );
[~,idx2] = sort( idx(1:6) );
y = y( idx2 );
There may be a slightly more elegant way, but that does the job.
  1 件のコメント
Hidir ABAY
Hidir ABAY 2016 年 7 月 27 日
Thank you very much I exactly understand what you said.

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

その他の回答 (1 件)

Paxorus Sahay
Paxorus Sahay 2016 年 7 月 27 日
This sliding insertion technique might be what you're looking for.
function [minima] = smallest(vec, n)
minima = vec(1:n);
[maxElem, idx] = findMax(minima);
for i = (n+1):length(vec)
if vec(i) < maxElem
minima(idx:end) = [minima(idx+1:end) vec(i)];
[maxElem, idx] = findMax(minima);
end
end
end
function [maxElem, firstIndex] = findMax(vec)
% assuming vec not empty
maxElem = max(vec);
allMatches = find(vec == max(vec));
firstIndex = allMatches(1);
end
Example usage:
x = [1, 4, 100, 3, 14, 56, 8, 90, 23, 2];
y = smallest(x, 6);

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by