2

Are there any Matlab function or general code to generate all the combinations of features of a three-variable polynomial equation with a degree of n? For three variable of degree 3, the combinations of features will be 1, x, y, z, x^2, y^2, z^2, xy,yz,zx, x^3, y^3, z^3, x^2y, y^2z, z^2x, xyz.... and so on.

I already have the Matlab code for two variable and n degree from Andrew Ng's machine learning course.

function out = mapFeature(X1, X2)
degree = 6;
out = ones(size(X1(:,1)));
for i = 1:degree
    for j = 0:i
        out(:, end+1) = (X1.^(i-j)).*(X2.^j);
    end
end

end

I was wondering if there is any code for three variable of n degree. Thanks in advance.

iAnas
  • 451
  • 1
  • 6
  • 9

2 Answers2

3

There is also a simple meshgrid - based solution:

degree = 3;
[i,j,k]= meshgrid(0:degree);
powers= sortrows([i(:) j(:) k(:)]);
out = [];
for m = 1:size(powers,1)
    d= powers(m,:);
    if sum(d)<=degree
        out(:, end+1) = (X1.^d(1)).*(X2.^d(2)).*(X3.^d(3));
    end
end

The meshgrid function generates three matrices containing 3D grid of the values of its argument. One can expand this matrices into columns and concatenate using [i(:) j(:) k(:)]. It gives us the matrix whose rows are the combinations of degrees. sortrows sorts the rows of the matrix to make the combination order more natural. There is also a multidimensional grid generation function ndgrid which an be used in the case of more than 3 variables.

AVK
  • 2,130
  • 3
  • 15
  • 25
2

You can choose the great function nmultichoosek from this other SO question

function combs = nmultichoosek(values, k)
%// Return number of multisubsets or actual multisubsets.
if numel(values)==1 
    n = values;
    combs = nchoosek(n+k-1,k);
else
    n = numel(values);
    combs = bsxfun(@minus, nchoosek(1:n+k-1,k), 0:k-1);
    combs = reshape(values(combs),[],k);
end

calling it as

combs=nmultichoosek([1 x1 x2 x3],4);

and removing all the values that do not have 1 in the first column

combs=combs(combs(:,1)==1,:);

finally computing the product of the columns

 result=prod(comb,2);

This works for any amount of n variables but it will get ugly with bigger n. Remember to change the 4 to n+1 if you change the variables.

Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
  • Thank you for helping out :) The last answer was easy to follow and worked for me. If I have time, I will look for yours also. Thanks again :) – iAnas Jul 27 '18 at 10:49
  • @iAnas the one you accepted is better than mine, no worries ;) – Ander Biguri Jul 27 '18 at 10:53