MATLAB: How to generate the kind of truth table described below

tabletruthtruthtable

Hi, I am having an issue trying to generate this kind of truthtable:
every letter indicates a specific device that it can have 2 or more states, and every device can have just one state active (not two or more active states at the same time):
In this example we have the device a with 2 states and the device b with 3 states, I want to write a script giving just this informations and generate a matrix like this: (with just one and zeros, obviously without a_0 a_1 b_0 b_1 b_2)
a_0 a_1 b_0 b_1 b_2
1 0 1 0 0
1 0 0 1 0
1 0 0 0 1
0 1 1 0 0
0 1 0 1 0
0 1 0 0 1
As you can see every device has only one active state in every combination, I need to generalize this process to an arbitrary number of devices everyone with an arbitrary number of states, and generating all possible combinations with the retrictions that i described above. Thank you very much for your help.

Best Answer

numstates = [2, 3, 2]; %three device example
num_orig = length(numstates);
[uniq_numstates, ~, ic] = unique(numstates);
num_uniq = length(uniq_numstates);
state_tables = cell(num_uniq,1);
idx_list = cell(num_uniq,1);
for K = 1 : num_uniq
state_tables{K} = toeplitz([1, zeros(1,uniq_numstates(K)-1)]);
idx_list{K} = 1:uniq_numstates(K);
end
[idxgrid{1:length(numstates)}] = ndgrid(idx_list{ic});
idxlist = cellfun(@(C) C(:), idxgrid, 'uniform', 0);
truth_table = cell2mat(arrayfun(@(K) state_tables{ic(K)}(idxlist{K},:), 1:num_orig, 'uniform',0));
The code optimizes by only creating the unique subtables -- e.g., in the above example the third device has 2 entries just like the first device does, and it is not necessary to build the sliding 1 table multiple times.
Construction of the sliding 1 table could be done incrementally from smallest to largest but it is not clear it would be any faster than the clearer method of calling toeplitz once per size.
The output order might not be exactly how you would prefer, but the list is exhaustive.