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.
답변 (1개)
Image Analyst
2015년 5월 27일
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에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!