How to compute cross terms

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?

 Risposta accettata

John D'Errico
John D'Errico il 21 Ago 2016
Modificato: John D'Errico il 21 Ago 2016
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.

1 Commento

Eugene
Eugene il 21 Ago 2016
Yes, thank you. I was thinking along these lines but you're observation that I only need the exponents was the best for avoiding working with numerical data (since I can't do a unique on numbers).
This put me on the correct path, so thanks!

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by