HelpOverFlow
HelpOverFlow

Reputation: 11

Matching or Sorting array rows in matlab

I have the follow array in Matlab:

-60528084   -60780607
-60497166   -60750204
-60466187   -60719738
-60435147   -60689209
-60404046   -60658618
-60372884   -60627965
-60341661   -60597249
-60310378   -60566472
-60279035   -60535633
-60247632   -60504732
-60216170   -60473770
-60184647   -60442747
-60153066   -60411663
-60121425   -60380518

I am in need of a code/function to sort this array like this:

            -60780607
            -60750204
            -60719738
            -60689209
            -60658618
            -60627965
            -60597249
            -60566472
-60528084   -60535633
-60497166   -60504732
-60466187   -60473770
-60435147   -60442747
-60404046   -60411663
-60372884   -60380518
-60341661   
-60310378   
-60279035   
-60247632   
-60216170   
-60184647   
-60153066   
-60121425

What this SORT does is to match the rows values that are very similar. The values are not same, but almost the same.

Upvotes: 0

Views: 190

Answers (2)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

Assuming you just want to find the best shift, here is what you can easily do:

  1. Start at a certain position, calculate how 'good' it is (for example average of squared nonzero neighbours) record the amount shifted
  2. Shift one further, check if it is better. If better remember this shift instead.
  3. If further shift is possible, repeat step 2.

Upvotes: 0

user2212608
user2212608

Reputation:

you can use:

[ms,ix]=sort(m(:))

to get both the entire sorted list and the linear indexes of the matrix m. Then you can use ind2sub to get the relevant columns of the sorted indices:

[r c]=ind2sub(size(m),ix);

then the difference of that sorted vector and set a proximity threshold (say 10000),

proximity_threshold=1e4; %# change as needed
ind=(diff(ms)<proximity_threshold)

then reconstruct your answer using a condition of the threshold:

n=0;
nn=0;
while n<numel(ix)
    n=n+1;
    nn=nn+1;
    try
        if ind(n) & c(n)~=c(n+1)
            a(nn,c(n))=ms(n);
            a(nn,c(n+1))=ms(n+1);
             n=n+1;

        else
            a(nn,c(n))=ms(n);

        end
    end
end


        a =
               0   -60780607
               0   -60750204
               0   -60719738
               0   -60689209
               0   -60658618
               0   -60627965
               0   -60597249
               0   -60566472
       -60528084   -60535633
       -60497166   -60504732
       -60466187   -60473770
       -60435147   -60442747
       -60404046   -60411663
       -60372884   -60380518
       -60341661           0
       -60310378           0
       -60279035           0
       -60247632           0
       -60216170           0
       -60184647           0
       -60153066           0

Upvotes: 2

Related Questions