sort function

5 views (last 30 days)
minoo
minoo on 2 May 2011
Hi everybody,
I have a problem and I'll be thankful if you can help me.
I've used "sort" function and I have sorted vector and also indices of sorted elements. I want to check if the sorted elements are in a row or not?!
I want to know if there is a better way than for loop and check it one by one!!

Accepted Answer

Matt Fig
Matt Fig on 2 May 2011
I think you will have to clarify your question more. What do you mean by "in a row?" Does this mean that they are integers separated by 1? What if there are repeats, does that count as "in a row?" Do you mean you want to know whether the elements in the sorted array are "in a row" or the elements in the original array?
%
%
%
EDIT In response to your clarification.
Look at using the DIFF function to produce a logical index:
A = [3 14 7 4 1 8 12 5]
[sorted,indices]=sort(A,'descend')
idx = [0 diff(indices)];
idx = abs(idx)==1
slct = indices(find(~idx,4)) % The first four non-consecutive indices.
Of course it could be that once this is done, the removal of an element of the indices vector could cause another set of consecutive elements to appear in the slct vector... If you really want to avoid this possibility, put the above in a WHILE loop, or just do the whole thing with a FOR loop to begin with...
  1 Comment
minoo
minoo on 2 May 2011
I need to sort a vector in descending order and use 4 first elements of the vector for my calculation but if two of them are in a row in the original vector, I should neglect one of these two and pick the fifth element of the vector.
I want to know whether the elements in the sorted array are in a row or sequential.
suppose
A = [3 14 7 4 1 8 12 5]
[sorted,indices]=sort(A,'descend')
and I will have
sorted = [14 12 8 7 5 4 3 1]
indices = [2 7 6 3 8 4 1 5]
as you see, the second and third elements in the indices are sequential and in this case I should neglect one of them.

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!