Say I have a matrix with 3 columns: c1, c2,c3, and I want to create a new matrix in which each column is any possible product of two of the columns of this matrix.
So, if I had a matrix with d columns, I would like to create a new matrix with d+d(d-1)/2+d columns. For example, consider the matrix with 3 columns c1, c2,c3. The matrix that I would like to create should have the columns c1, c2,c3, c1xc2, c2xc3,c1xc3, c1^2, c2^2 and c3^2.
Is there any efficient way to do this?
I’m embarrassed to post this – I’m sure there must be a simpler way (there is a MUCH simpler way – see my december update at the bottom of the answer), but this will do the job:
The calculation is not efficient, since in the
Bstep I actually calculate double the number of combinations that I need (ie I get c1.*c1, c1.*c2, c1.*c3, c2.*c1, c2.*c2, c2.*c3, c3.*c1, c3.*c2, c3.*c3), and then in the second step I pull out only the columns that I need (eg I get rid of c3.*c1 as I’ve already got c1.*c3 and so on).UPDATE: Was just out driving and a much better method occurred to me. You just need to construct two index vectors of the form:
I1 = [1 1 1 2 2 3]andI2 = [1 2 3 2 3 3], then(A(:, I1) .* A(:, I2))will get you all the column products you are after. I’m away from my computer at the moment, but will come back later and work out a general way to construct the index vectors. I think it can be fairly easily accompished using thetril(toeplitz)construction. Cheers. Will update in a few hours.UPDATE: Rody’s second solution (+1) is exactly what I had in mind with my previous update so I won’t bother repeating what he has done there now. Yoda’s is quite neat too actually, so another +1.
DECEMBER UPDATE: Funnily enough, after working on it here, I had to revisit this problem for my own research (coding up White’s test for heteroscedasticity). I’m actually favoring a new approach now, recommended (somewhat cryptically) by @slayton in the comments. Specifically, using
nchoosek. My new solution looks like this:nchoosekyields exactly the indices we need to construct the cross-products quickly and easily!