MATLAB: How to convert Cell Array index into Matrix with ones

cellcell arraycell arrays

I have cell array of A having values
A {1,1} = [2]
A {1,2) = [2, 3]
A {1,3} = [3]
A {1,4} = [3, 4]
Based on this information, I want to make two matrix B such that values of cell array A converts into ones as per below B = [ 0 1 0 0; 0 1 1 0; 0 0 1 0; 0 0 1 1]

Best Answer

The simple way:
A = {2, [2, 3], 3, [3, 4]};
B = zeros(numel(A), max(cat(2, A{:}))); % Pre-allocate
for iRow = 1:numel(A)
B(iRow, A{iRow}) = 1;
end
A vectorized way:
% UNTESTED
nA = cellfun('length', A);
col = cat(2, A{:});
row = repelem(1:numel(A), nA);
sizeB = [numel(A), max(cat(2, A{:}))];
index = sub2ind(sizeB, row, col);
B(index) = 1;