function CPT = mk_CPT_from_mux(gate, input, arity)
% MK_CPT_FROM_MUX Make a CPT representation of a multiplexer
% CPT = mk_CPT_from_mux(gate, input, arity)

n = length(input);
an = arity^n;
CPT = zeros(an, n, arity);
U = ind2subv(arity*ones(1,n), 1:an);
for g=1:n
  % tmp(i, U(i,g)) = 1, where tmp is A^n * A in size
  tmp = sparse(1:an, U(:,g), ones(an,1), an, arity);
  %tmp = zeros(an, arity);
  %ind = subv2ind([an n], [(1:an)' U(:,g)]);
  %tmp(ind) = 1;
  CPT(:,g,:) = full(tmp);
end
CPT = reshape(CPT, [arity*ones(1, n) n arity]);

% We may need to re-order the dimensions to be consistent with the node numbering.
% e.g., gate = 1, input = 2:3
% Then we need to put the gate's dimension (assumed to be n+1=3 above) first.
if gate < input
  perm = [n+1 1:n n+2];
  CPT = permute(CPT, perm);
end
