Convert cell array to double, with comma separated elements

34 views (last 30 days)
France
France on 18 Mar 2020
Edited: Guillaume on 19 Mar 2020
Hello guys,
I have got a cell array like the follow:
'1.265000e+02, 2.505000e+02, 22, 27, '
'1.275000e+02, 2.505000e+02, 20, 29, '
'1.275000e+02, 2.525000e+02, 20, 25, '
...
I need to convert it in double (or uint8). The outup should be:
[126.5, 250.5, 22, 27]
What I need is that all the values must be in a single cell and that a comma separeted any value. The last comma from any cell should be removed.
L'output in double/ uint8
Can you please help me? Many thanks in advance!!
  2 Comments

Sign in to comment.

Answers (2)

dpb
dpb on 18 Mar 2020
>> v=cell2mat(cellfun(@(s) sscanf(s,'%f,').',c,'UniformOutput',false))
v =
126.5000 250.5000 22.0000 27.0000
127.5000 250.5000 20.0000 29.0000
127.5000 252.5000 20.0000 25.0000
>>
However, it would probably be better to read the data in numerically instead...how did you obtain the above cell content?
  12 Comments

Sign in to comment.


Sajeer Modavan
Sajeer Modavan on 18 Mar 2020
I hope you are looking this
A = ['1.265000e+02, 2.505000e+02, 22, 27, '
'1.275000e+02, 2.505000e+02, 20, 29, '
'1.275000e+02, 2.525000e+02, 20, 25, '];
str2num(A(1,:))
  6 Comments
Guillaume
Guillaume on 19 Mar 2020
"your cell array is not like what I wrote"
You did not write a cell array! Your A is a 2D char vector. That's very different. The cell array would be:
A = {'1.265000e+02, 2.505000e+02, 22, 27, ';
'1.275000e+02, 2.505000e+02, 20, 29, ';
'1.275000e+02, 2.525000e+02, 20, 25, '};
Note the use of {} not [].
"if you make it in this format, then it will work sure,"
Except it is impossible to construct a 2D char vectors with rows of different length:
>> A = ['1.265000e+02, 2.505000e+02, 22, 27.5, '; %<--- longer row here
'1.275000e+02, 2.505000e+02, 20, 29, ';
'1.275000e+02, 2.525000e+02, 20, 25, '];
Error using vertcat
Dimensions of arrays being concatenated are not
consistent.
whereas it's not an issue with cell arrays:
>> A = {'1.265000e+02, 2.505000e+02, 22, 27.5, '; %<--- longer row here
'1.275000e+02, 2.505000e+02, 20, 29, ';
'1.275000e+02, 2.525000e+02, 20, 25, '}; %does not generate an error

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!