Reputation: 1501
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?
Upvotes: 0
Views: 447
Reputation: 56
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 ]
Upvotes: 1