sort and eliminate elements

I have a array of 1XN positive numbers which are very closed numbers. I tried to sort them in rising order by eliminating the non-rising order elements. For example, N=20
and
A=
[4.522119728
5.080599083
5.105557046
5.063978752
5.991930715
5.052086095
6.057840556
5.901693267
5.149232851
4.99253134
5.065569374
5.051748207
5.382426394
5.042862762
4.918077391
5.402468089
5.09548983
5.019724889
5.25911928
5.143977878];
I did a for loop as below:
for i=1:length(A)-1
if A(i+1)<=A(i)
A(i+1)=0;
end
end
ind=find(A==0);
A(ind)=[];
However, if A(1)<A(2) and I eliminate A(1) instead of keeping A(1) as the above for loop does, I may end up keep more elements in A. Therefore, I'll make the above for-loop a function. For instance, as N=5000, I need to make a big for-loop to check from A(i) to A(5000) and look for 5000 answers of new As, then compare the length of new As and keep the longest new As.
Is there other more efficient ways?
Thanks.

2 个评论

In this case, I need to sort the array by deleting some elements and finally 1)keep as most element possible and 2)all the elements are monotonically increasing.So the above method can only guarantee monotonically increasing order, but not guarantee keeping the maximum possible elements.
Regards,
Limei
Keeping the most possible elements with result monotonically increasing is simply
B=sort(A); % <chuckles...>
Now, what you're looking for is those remaining if don't reorder but select a subset such that the selected subset is sorted ascending?

请先登录,再进行评论。

回答(1 个)

You can do it this way:
A=...
[4.522119728
5.080599083
5.105557046
5.063978752
5.991930715
5.052086095
6.057840556
5.901693267
5.149232851
4.99253134
5.065569374
5.051748207
5.382426394
5.042862762
4.918077391
5.402468089
5.09548983
5.019724889
5.25911928
5.143977878];
% Initialize
peakValue = A(1);
rowsToKeep = [];
for row = 1 : length(A)
% Check if this value is more than the prior peak.
if A(row) >= peakValue
% It is greater. Save this row number.
rowsToKeep = [rowsToKeep, row];
% Update the peak value.
peakValue = A(row);
end
end
% Extract only those values that we need.
output = A(rowsToKeep)

类别

帮助中心File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

提问:

2015-5-26

Community Treasure Hunt

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

Start Hunting!

Translated by