MATLAB: How to compute cross terms

cross termspolynomial

Is there a function to compute cross terms of a vector? For example, if I have (symbolically) a = [ a1, a2, a3];
Then the cross terms of a for order 2 would be:
[ a1^2, a2^2, a3^2, a1*a2, a1*a3, a2*a3]
And cross terms for order 3 would be:
[ a1^3, a1^2*a2, a1^2*a3, a1*a2^2, a1*a2*a3, a1*a3^2, a1^2*a2, a1*a2^2, a1*a2*a3, a2^3, a2^2*a3, a2*a3^2, a1^2*a3, a1*a2*a3, a1*a3^2, a2^2*a3, a2*a3^2, a3^3] (this contains duplicates which I want to avoid)
It's very close to the expansion of (a1+a2+a3)^3, but I want the individual terms instead of the sum. I also want it numerically, but symbolically would work if I can convert it.
Is there a Matlab function that takes a vector and computes these cross terms?

Best Answer

Easy enough to do it with a loop. All that you need are the exponents. If you really want the symbolic forms later, trivial for that too.
function XT = xterms(N,nv)
% compute all cross terms of order N for nv variables.
XT = zeros(1,nv);
for n = 1:N
XTnew = zeros(0,nv);
for m = 1:nv
XTm = XT;
XTm(:,m) = XTm(:,m) + 1;
XTnew = [XTnew;XTm];
end
XT = unique(XTnew,'rows');
end
So:
xt = xterms(2,3)
xt =
0 0 2
0 1 1
0 2 0
1 0 1
1 1 0
2 0 0
If you want a symbolic form for each term, (it is a REALLY bad idea to create numbered variables, so I do not advise it.) But this is trivial too.
syms a1 a2 a3
prod(repmat([a1 a2 a3],size(xt,1),1).^xt,2)
ans =
a3^2
a2*a3
a2^2
a1*a3
a1*a2
a1^2
As I said, the exponent array is all that you really need for any computations.