TravellingSalesWoman
TravellingSalesWoman

Reputation: 133

convert from array of cells to a matrix

I have a msg of size 1227
each cell inside it has a row of data. each row with different size I want to create a matrix with 1227 rows each row from a different cell

how can I do that ?

Upvotes: 0

Views: 42

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

In a matrix, by definition, all rows have the same length. You have to fill with values, such as NaN:

data = {1:3, 4:5, 6:9}; %// example data
M = numel(data); %// number of rows
N = max(cellfun(@numel, data)); %// maximum number of columns
matrix = NaN(M, N); %// initiallize with NaN (used as fill value)
for m = 1:M
    row = data{m}; %// extract values of cell
    matrix(m, 1:numel(row)) = row; %// write to first entries of matrix row
end

In this example,

>> celldisp(data)
data{1} =
     1     2     3
data{2} =
     4     5
data{3} =
     6     7     8     9

>> matrix
matrix =
     1     2     3   NaN
     4     5   NaN   NaN
     6     7     8     9

Upvotes: 1

Related Questions