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:
- Sort the elements of
Ainto 5 quintiles; - Pick the first
group of elements in
A, get the corresponding values inB; - Sort the picked elements of
Binto 5 groups. - Take the average of each group from
C. - Pick the second group of elements in
A, get the corresponding values inB; - Sort the picked elements of
Binto 5 groups. - Take the average of each group from
C. - 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.