Convert cell array to matrix

3 次查看(过去 30 天)
Antonio Sereira
Antonio Sereira 2017-4-5
Hi!
I have a 1x100 cell array A and each cell has a different size, e.g. in cell 1 there are 5 numbers 23,24,66,78,55 and in cell 2 there are 6 numbers 4,10,22,65,44,2. Now I want to convert the cell array into a 2D matrix B with size 100x60. The point is that the numbers in cell 1 corresponds to the jth column of the row 1 in the matrix B. In that way I get zeros in the first row but ones at the 23th,24th,66th,78th and 55th columns of the first row.
How I can do this?
For information: The array A I got from findpeaks, where I used a for loop and scanned a 100x60 matrix row by row and selected all maximas above a threshold.
  1 个评论
Akira Agata
Akira Agata 2017-6-14
If my understanding is correct,the matrix B should be 100x100. If so, the following code will generate the matrix B which I believe is what you want.
B = zeros(100,100);
for kk = 1:100
idx = false(100,1);
idx(A{kk}) = true;
B(idx,kk) = 1;
end
Is my understanding correct?

请先登录,再进行评论。

回答(1 个)

Andrei Bobrov
Andrei Bobrov 2017-6-14
m = max(cellfun(@max,A));
n = numel(A);
B = zeros(m,n);
B(sub2ind([m,n],[A{:}],repelem(1:numel(A),cellfun(@numel,A)))) = 1;
B = B';

Community Treasure Hunt

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

Start Hunting!

Translated by