Nested double sort in Matlab

Viewed 940

Suppose I have 3 vectors, vector A which is (n x 1), vector B which is (n x 1) and vector C which is (n x 1).

I want to sort the elements of A, into 5 groups, and then within those groups I want to sort the respective elements of B into 5 groups as well. And then take the average of the elements in C. So I will have 25 averages.

In other words:

  1. Sort the elements of A into 5 quintiles;
  2. Pick the first group of elements in A, get the corresponding values in B;
  3. Sort the picked elements of B into 5 groups.
  4. Take the average of each group from C.
  5. Pick the second group of elements in A, get the corresponding values in B;
  6. Sort the picked elements of B into 5 groups.
  7. Take the average of each group from C.
  8. And so on and so forth.

Here's my dummy code for this:

minimum = 50;
maximum = 100;

A = (maximum-minimum).*rand(1000,1) + minimum;
B = (maximum-minimum).*rand(1000,1) + minimum;
C = (maximum-minimum).*rand(1000,1) + minimum;


nbins1 = 5; 
nbins2 = 5;

bins1 = ceil(nbins1 * tiedrank(A) / length(A));

for i=1:nbins1

    B1 = B(bins1==i);
    C1 = C(bins1==i);
    bins2 = ceil(nbins1 * tiedrank(B1) / length(B1));

    for j=1:nbins2
        C2 = C1(bins2==j);
        output(i,j) = mean(C2);
        clearvars  C2 
    end


    clearvars B1 C1
end

The issue is that, this does not seem very elegant or efficient at all. Is there any other way of doing this? For people in Finance, this problem is analogous to the Fama-French (1993) double sorting of portfolios.

1 Answers
Related