Effacer les filtres
Effacer les filtres

How to convert Cell Array index into Matrix with ones

3 vues (au cours des 30 derniers jours)
Vishal Sharma
Vishal Sharma le 21 Fév 2017
Modifié(e) : Jan le 21 Fév 2017
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]

Réponse acceptée

Jan
Jan le 21 Fév 2017
Modifié(e) : Jan le 21 Fév 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;

Plus de réponses (0)

Catégories

En savoir plus sur Data Types dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by