How to convert Cell Array index into Matrix with ones

3 Ansichten (letzte 30 Tage)
Vishal Sharma
Vishal Sharma am 21 Feb. 2017
Bearbeitet: Jan am 21 Feb. 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]

Akzeptierte Antwort

Jan
Jan am 21 Feb. 2017
Bearbeitet: Jan am 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;

Weitere Antworten (0)

Kategorien

Mehr zu Data Types finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by