Converting from cell arrays to matrices in MATLAB

July 10th, 2009 | Categories: matlab | Tags:

I had a query from a MATLAB user the other day and I thought I would share it with the world just in case it turned out to be useful to someone.  She had some data in a cell array that appeared as follows

data =

    '-0.000252594'
    '-0.788638'
    '-1.14636'
    '-1.15374'
    '-1.15474'

I’m not sure how she ended up with her data in this form but that’s not important here. What is important is that she couldn’t calculate with it in all the ways she was used to so what she asked was ‘how do I convert this cell array to a matrix?

It turns out that this is relatively easy to do since this particular cell array has a very simple form.  If you want to follow along then you can create an identical cell array as follows

data={'-0.000252594'; '-0.788638'; '-1.14636' ;'-1.15374' ;'-1.15474'}

data =

    '-0.000252594'
    '-0.788638'
    '-1.14636'
    '-1.15374'
    '-1.15474'

Let’s check that this really is a cell array using the iscell() function

iscell(data)

ans =
     1

Looks good so far. So, to convert this to a matrix all you need to do is

matdata=cellfun(@str2num,data)

matdata =
   -0.0003
   -0.7886
   -1.1464
   -1.1537
   -1.1547

the variable matdata is a standard MATLAB matrix and to prove it I’ll add 1 to all of the elements in the usual fashion

matdata+1

ans =
    0.9997
    0.2114
   -0.1464
   -0.1537
   -0.1547

That’s it! If only all queries were that simple :)

  1. July 10th, 2009 at 20:10
    Reply | Quote | #1

    thank you for posting this because it’s really handy to know.

    i’m curious about the loss of precision during the conversion, though. do you know how to preserve the original precision?

    cheers

  2. Mike Croucher
    July 13th, 2009 at 09:34
    Reply | Quote | #2

    Hi Ravian

    There’s no loss of precision – it just looks that way. If you use ‘format long’ then you’ll see the full precision:

    format long
    >> matdata
    
    matdata =
      -0.000252594000000
      -0.788638000000000
      -1.146360000000000
      -1.153740000000000
      -1.154740000000000
    
    
  3. John
    July 21st, 2009 at 04:23
    Reply | Quote | #3

    My data actually looks like:

    data =

    [-0.0263]
    [-0.0266]
    [-0.0260]
    [-0.0240]
    [-0.0219]
    [-0.0198]
    [-0.0105]

    How can I convert this ‘cell’ data into numbers?

  4. Mike Croucher
    July 21st, 2009 at 09:23
    Reply | Quote | #4

    Hi John

    Since your cell consists of a set of numbers rather than strings then the following should do the trick

    cell2mat(data)
    
  5. John
    July 21st, 2009 at 21:40
    Reply | Quote | #5

    it works! thanks.

  6. ron dragon
    February 16th, 2010 at 14:43
    Reply | Quote | #6

    Brilliant – thanks!

  7. reen
    May 20th, 2010 at 16:44
    Reply | Quote | #7

    I have the following *.txt file:

    header1;
    header2;
    1031,-948,-76, ,”12″
    507,635,-1148, ,”34″
    -1031,948,750, ,”45″
    -507,-635,114, ,”67″

    My interested data is:
    1031,-948,-76
    507,635,-1148
    -1031,948,750
    -507,-635,114

    I tried to use csvread but failed.
    How to get interested data

    regards

  8. May 21st, 2010 at 14:10
    Reply | Quote | #8

    Hi reen

    Your question inspired a mini-tutorial on csv files. Find the solution to your question at the link below

    http://www.walkingrandomly.com/?p=2654

    best wishes,
    Mike

  9. Megha Bhatt
    June 1st, 2010 at 12:19
    Reply | Quote | #9

    Hi,
    Thanks for your simple explanation about how to convert a cell array into numbers. It helped me in solving my problem in MATLAB.

  10. Navin
    July 14th, 2010 at 11:17

    Thanks a lot! Conversion from cellarray to matlab matrices has been a puzzler for quite a while for me. This page really helped :)
    And if you assume that for every person who posted here, there would be a corresponding thousand people who benefited from this site and did not post, then you’ve helped an immensely huge amount of people! Coz MATLAB is so widely used.

  11. nayla
    November 10th, 2010 at 22:47

    I have a matrix cell that contains 3 colomns and 3 rows
    TP1 a b
    TP1 a b
    TP2 a c
    i want to have a new matrix that contains only TP1 a b and TP2 a c,so i have to ommit either the first row or the second
    i wanted to use the function unique rows but it say i can’t apply it for cell,i should apply it for double, i tried to change my cell matrix to double but it didnt work
    if someone could help me thanks a lot

  12. Shailen TJ
    December 3rd, 2010 at 00:39

    Hello,

    I have a cell with this information:
    A=
    ‘1;12;2;0;2384;0’

    iscell(A)
    ans= 1

    I want to create an array/matrix such that B is [1 12 2 0 2384 0]

    I have spent a few hours already. Any ideas?

    Much appreciated

    Shailen.

  13. December 5th, 2010 at 12:11

    Hi Shailen

    So, am I right in saying that the cell element contains a string. I.e. do you get

    >> class(A{1})
    ans =
    char
    

    Such a cell could be created, for example, by

    A={'1;12;2;0;2384;0'}
    

    If this is what you have then you can get your matrix B by doing

    B=str2num(A{1})'
    B =
               1          12           2           0        2384           0
    

    Does this help?

    Mike

  14. Sarah
    March 8th, 2011 at 20:12

    Hi, I have a cell array & was able to convert most of it to a matlab array using your example above (thanks!), but the first and last elements have a leading & trailing character that I need to get rid of, so for your example above it would look like:

    data
        '{-0.000252594'
        '-0.788638'
        '-1.14636'
        '-1.15374'
        '-1.15474}'
    

    I got to here by spliting a long string using: data = regexp(tmp,’\,’,’split’);
    Thanks for any help!
    Sarah

  15. March 10th, 2011 at 20:00

    Hi Sarah

    Can you email me the code? Contact details at
    http://www.walkingrandomly.com/?page_id=2055
    Cheers,
    Mike

  16. April 11th, 2011 at 10:23

    how to convert a text file into a matrix.

  17. tahere
    June 3rd, 2011 at 21:22

    hi
    when i want to use ellfun fo my data ,this error is appeare please guide me!
    >> matdata=cellfun(@str2num,textdata)
    ??? Error using ==> cellfun
    Non-scalar in Uniform output, at index 1461547, output 1.
    Set ‘UniformOutput’ to false.

  18. vrushali
    July 19th, 2011 at 11:34

    Hi,
    I have doubt regarding cell array to matrix. I have data in excel file which contains data log of speed Vs time. I converted the name field of data (like Speed, Time) into character array. and data in to cell array(cell array inside cell array). No I want to concatenate both into matrix. how can i do this?

  19. Craig
    October 8th, 2011 at 02:25

    Thanks for this. The same problem had me puzzled for nearly an hour.

  20. benyamin.norouzi
    October 13th, 2011 at 12:56

    very thanks

    I need the code for produce random number in matlab for 0 to 255
    no with rand

  21. Hem
    November 9th, 2011 at 14:09

    Mike,

    I am working on an image processing project. I have obtained a cell array as output of an operation. I has cell arrays within itself like:
    cell with 2×2 double as its elements.
    cell with 4×4 double as its elements and one [ ] matrix.
    cell with 8×8 double as its elements and [ ] matrix.
    cell with 16×16 double as its elements and [ ] matrix.
    cell with 32×32 double as its elements and [ ] matrix.

    all i need is to obtain four 256×256 matrices using the contents of the obtained cell arrays.

    Regards,
    Hem

  22. Alexander
    December 12th, 2011 at 00:30

    Exceedingly helpful — this made my night.

  23. gamra
    February 18th, 2012 at 20:06

    could someone help me with this please?

    I have a file with numbers (similar to the one below):

    PE_val1 =

    2
    3
    4
    5
    7
    9
    7
    8
    9
    Now I want to convert this column of numbers to a matrix so that I can call the content of each element by PE_val1(i,j) where i is the number of row and i the number of column…Would someone help me please with this?

    Regards
    Gamra

  24. Avinash
    March 19th, 2012 at 06:24

    Hi…. help me with the foll matlab code :
    % read multiple images
    files = dir(‘*.jpg’);
    %to know how many images read :
    num_files = numel(files)
    = 8
    % so 8 images which are .jpg images are read

    images = cell(1, num_files)
    for k = 1:num_files
    images{k} = imread(files(k).name);
    end

    % for the above imread, i am getting error saying ‘unable to open the file to read – may be because you dont have read permission’ But i checked the images properties- it showed i have read only permission…dont know why i was unable to read. Is the code ok ? %

  25. Braden Rooke
    May 7th, 2013 at 23:48

    Much head scratching occurred prior to finding this. Thanks a bunch!

  26. Ashraf
    May 29th, 2013 at 21:10

    I have the following array
    val(:,:,1) = [145][2.0101e-09] [-6] [1×1 cfit] [1×1 struct] [0.5170]
    ….
    val(:,:,100) =[144][6.0301e-09][0][1×1 cfit] [1×1 struct][0.6009]

    how can I print this array to txt or convert this array to a matrix???
    help please

  27. Mike Croucher
    May 30th, 2013 at 10:35

    Ashraf

    Could you contact me via email ( http://www.walkingrandomly.com/?page_id=2055 ) and I’ll see what I can do for you.

    Cheers,
    Mike

  28. Ashraf
    June 9th, 2013 at 11:45

    Dear Mike,
    thanks for the help offer. I had solved the problem.
    Cheers,

  29. chaza
    July 14th, 2013 at 15:15

    hey everyone,
    when i import data from excell i get data and textdata in matlab and one column in textdata is time (‘9:40:31’) as exemple, in character format. i need to convert time such as ‘9:40:31’ in this column into numbers in seconds. is there a way to do this?
    thank you!