0
A= [1,  1,  1,  2,  3,  0,  0,  0];
B= [1, 2, 3 , 3, 3 , 4 , 4, 4];

A is the array I have and I want to arrange it so that A would look like:

A= [3,  2,  1,  1,  1,  0,  0,  0]; OR
A= [3,  2,  0,  0,  0,  1,  1,  1]; 

The point being that I know (from B) there is 1 unique number at the start, then 1 other unique, then 3 unique and another three unique numbers. If A does not fit that profile then I quit. Is there some Matlab function to handle this kind of sorting?

2
  • Each number in B represents a different number. Commented Sep 9, 2016 at 17:45
  • no typo, I know from B that there should be one unique number and 1 other unique number followed by three unique numbers and another three. Each number in B represents 1 unique number, where there are four in total. Commented Sep 9, 2016 at 17:57

1 Answer 1

1

I believe this function is what you are after. It sorts A such that the number of times Asort(i) appears within A matches the number of times B(i) appears within B for all i.

function [ Asort] = numsort( A, B)

A=sort(A);

for i=1:length(A);
numA(i)=length(find(A==A(i)));
numB(i)=length(find(B==B(i)));

end

[numAsort,f1]=sort(numA);
[numBsort,f2]=sort(numB);

if isequal(numAsort,numBsort);
    Asort1=A(f1);
    for i=1:length(A);
        Asort(f2(i))=Asort1(i);
    end

else 
    error('error')    
end

end

Using your vectors A and B, running the function I get:

Asort = [ 2     3     0     0     0     1     1     1 ]
Sign up to request clarification or add additional context in comments.

2 Comments

seems fine but your else part is incorrect. MATLAB will give error if the condition isequal(numAsort,numBsort) is false. Instead you may want to change else part with this: Asort='error'
That was my intention. The point is you can change exactly what the function does during the failure condition, but the function can't return a valid vector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.