% MAKETERMS % Create a list of all ways of representing a given integer n, % as a sum of k integer terms, each having value within [minx,maxx]. % % Simple recursive solution for illustration purposes. % (There might be more efficient methods.) % % Used for computing histogram probabilities. % % You can also use this for the Lecture6B sum-of-three-dice example % to list the cases: maketerms(5,3,1,6). % function X=maketerms(n, k, minx, maxx) if nargin<3, minx=0; end if nargin<4, maxx=n; end if k==1 if minx<=n && n<=maxx X = [n]; else X = zeros(0,1); end return end firstmin = max(minx, n-(k-1)*maxx); firstmax = min(maxx, n-(k-1)*minx); X = zeros(0,k); for first = firstmin:firstmax Y = maketerms(n-first, k-1, minx, maxx); Y = [repmat(first, size(Y,1), 1) Y]; X = [X; Y]; end