MATLAB: How to build a num array

str2num table

Hello,
I have following situation, from a database I got following table:
table (1,1) = {'[-7.045866760858189, -6.961728203539678, -6.378816032116447]'}
How can I create a num table with a array of each value?
Tablenew (1,1) = -7.045866760858189
Tablenew (1,2) = -6.961728203539678

Best Answer

The below solution assumes that there are the same number of entries in each row, but does not depend upon there being exactly 3.
format long g
Table(:,1) = {'[-7.045866760858189, -6.961728203539678, -6.378816032116447]';
'[-3.13423, -5.5512435, -99.999999999]'}
Table = 2x1 cell array
{'[-7.045866760858189, -6.961728203539678, -6.378816032116447]'} {'[-3.13423, -5.5512435, -99.999999999]' }
Tablenew = cell2mat(cellfun(@str2num, Table(:,1), 'uniform', 0))
Tablenew = 2×3
-7.04586676085819 -6.96172820353968 -6.37881603211645 -3.13423 -5.5512435 -99.999999999
Tthe str2num() will eval() each line, and if a line happened to contain something like 'rmdir(".")' then it would be happy to delete your directory.
The below solution assumes that there are exactly 3. It is a more secure solution. It could be generalized with not a lot work for the case where the number per line was consistent but not necessarily 3.
cell2mat(textscan(strjoin(Table(:,1)), '[%f,%f,%f]'))
ans = 2×3
-7.04586676085819 -6.96172820353968 -6.37881603211645 -3.13423 -5.5512435 -99.999999999