Search code examples
arraysregexmatlabmatrixcell-array

Cell array to matrix conversion in matlab


I would like to covert three <1xN cell> (A, B and C) into a single Nx3 matrix. Could someone help me with this?

C={{1xN}; {1xN}; {1xN}};

where each N is a number in single quotes, e.g.

C = {{'123123' ,'12324', ....N times}; {'123123', '12324', ....N times}; {'123123', '12324' ,....N times}}

Since a couple of them mentioned about the ridiculous input, this is the reason for having it in the above form.

The three nested array of cells are the results of a regexp where my string and expression are both strings. Therefore I have the output of regexp as three cell arrays of row vectors. For e.g.

node_ids=regexp(nodes,'(?<=node id=")\d*','match');

I can use cat function and then use a str2double for all three cell arrays and finally form a matrix by cell2mat. For e.g.

node_ids=cat(1,node_ids{:});node_ids=str2double(node_ids);

But this takes more time and has more LOC. My question is can it be done with fewer lines of code?

I tried using the cat function but keep getting this error:

Cannot support cell arrays containing cell arrays or objects.


Solution

  • Your input data is pretty bad.... why are you using a nested array of cells where each element is a string?

    In any case, assuming C is your original input data, do this:

    C = {{'123123' '12324'}; {'123123' '12324'}; {'123123' '12324'}};
    out = cellfun(@(x) cellfun(@str2num, x, 'uni', 0), C, 'uni', 0);
    out = cell2mat(cellfun(@cell2mat, out, 'uni', 0));
    

    First line is some dummy data. Next line first goes through every nested cell element over your cell array and converts the strings into numbers. However, these are still in cell arrays. As such, the next line converts each cell array in the nested cell into a matrix, then we merge all of the cells together into one final matrix.

    We get:

    >> out
    
    out =
    
          123123       12324
          123123       12324
          123123       12324