MATLAB: Generating all possible pairs of polynomial

ndgrid

Basically what I want to do is similar to here https://uk.mathworks.com/matlabcentral/answers/267009-generating-all-possible-pairs-of-polynomial-interaction-combinations i.e. I want to generate all possible power polinomial witch each term less than a certain number. My code is here
clear all
clc
%%input;
mu=7;
my=7;
me=7;
delay=1;
degree=2;
totalD=my+mu+me;
A = cell(totalD,1);
[A{1:totalD}] = ndgrid([0:degree]);
for k=1:totalD
polyPow(:,k)=reshape(A{k},[],1);
end
polyPow(sum(polyPow,2)>degree,:) = [];
The problem I am facing now. If the inputs mu,my, and me (also degree) are a bit big, the matrix A becomes very large and I got error "Requested 3x3x3x3x3x3x3x3x3x3x3x3x3x3x3x3x3x3x3x3x3 (77.9GB) array exceeds maximum array size preference". Anyone has a better idea for my purpose?
Thank you

Best Answer

The big problem is that you are throwing out most of your array. The method I use below does that as well, but much less so, making it faster (except for small cases) and more memory-efficient. There are probably way to make this code better, and it is sorely lacking in comments explaining what I'm doing, but it's getting late. If you need some explanation, just comment below this question and I'll edit in comments.
%~ shared setup ~%
clc,clearvars%better than clear all, better still is to use functions
mu=7;
my=7;
me=7;
delay=1;
degree=2;
totalD=my+mu+me;
%~ my code ~%
v=sort(repmat(1:(totalD+1),1,degree+1))-1;
selection=unique(nchoosek(v,degree+1),'rows');
polyPow=zeros(size(selection,1),totalD);
for row=1:size(selection,1)
for col=1:size(selection,2)
if selection(row,col)~=0
c=selection(row,col);
polyPow(row,c)=polyPow(row,c)+1;
end
end
end
polyPow(sum(polyPow,2)>degree,:) = [];
polyPow=unique(polyPow,'rows');
try
%~ your code ~%
A = cell(totalD,1);
[A{1:totalD}] = ndgrid([0:degree]);
polyPow_old=[];
for k=1:totalD
polyPow_old(:,k)=reshape(A{k},[],1);
end
polyPow_old(sum(polyPow_old,2)>degree,:) = [];
catch
polyPow_old=[];
end
%~ check equivalence ~%
if ~isequal(sortrows(polyPow),sortrows(polyPow_old))
if ~isempty(polyPow_old)
error('oops')
end
end