Azzera filtri
Azzera filtri

How to convert Cell Array index into Matrix with ones

3 visualizzazioni (ultimi 30 giorni)
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]

Risposta accettata

Jan
Jan il 21 Feb 2017
Modificato: Jan il 21 Feb 2017
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;

Più risposte (0)

Categorie

Scopri di più su Data Types in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by