Converting from cell arrays to matrices in MATLAB
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

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
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:
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?
Hi John
Since your cell consists of a set of numbers rather than strings then the following should do the trick
it works! thanks.
Brilliant – thanks!
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
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
Hi,
Thanks for your simple explanation about how to convert a cell array into numbers. It helped me in solving my problem in MATLAB.
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.