How to convert Cell Array index into Matrix with ones

1 次查看(过去 30 天)
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]

采纳的回答

Jan
Jan 2017-2-21
编辑:Jan 2017-2-21
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;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by