I do not know MATLAB and your requirement is not very clear but the following C code achieves the output of the examples
int u = 0x0d; int k = 4;
int l, result;
for(l = 1 << (k - 1); l != 0; l >>= 1)
{
result = u ^ l; }
the above code also works for second example with 3 bits with of course appropriate changes in value of u and k.