How to convert cell array into numerical array correctly with precision(no roundup value)?

4 vues (au cours des 30 derniers jours)
Hello,
I need to convert cell array into numerical array correctly with precision(no roundup value). I have tried various ways to get it right but couldn't. Any help is much appreciated.
Input:
L = {'38.95676800902' '38.95676807489' '38.95676821300' '38.95676838920' '38.95676853021'}
Desired output:
L_out= [38.95676800902 38.95676807489 38.95676821300 38.95676838920 38.95676853021]
*I used three methods but I am not getting it right,
1: Using cell2mat %This shows the output I got in Char instead of double(number), I am collecting output using counter in this case as it shows only one value instead of array when used this function.
L_out =
33333
88888
.....
99999
55555
66666
77777
66666
88888
00235
07183
94390
08022
29001
2: Using printf and scanf
S = sprintf('%s ', L{:}); L_out = double(sscanf(S, '%f'));
L_out = [38.9567 38.9567 38.9567 38.9567 38.9567]
This one is not accurate at all for my purpose
3. Using str2double
L_out = [38.9567 38.9567 38.9567 38.9567 38.9567]
In this way again I am not getting it accurate.
Is there a way to get it right?

Réponse acceptée

Guillaume
Guillaume le 18 Mar 2015
The correct and fastest way to convert a cell array of strings into a matrix of number is indeed with str2double
>>L = {'38.95676800902' '38.95676807489' '38.95676821300' '38.95676838920' '38.95676853021'}
>>L_out = str2double(L)
L_out =
38.95676800902 38.95676807489 38.956768213 38.9567683892 38.95676853021
This will convert the strings to the nearest number representable by a double (some numbers such as 0.1 can't be represented exactly as double).
In this way again I am not getting it accurate.
Yes, you are. The format matlab uses to display numbers has no bearing on the actual value stored in the number. Change the display format with format and you'll see the number are as accurate as can be.
>>format short g;
>>L_out
L_out =
38.957 38.957 38.957 38.957 38.957
>>format long g
>> L_out
L_out =
38.95676800902 38.95676807489 38.956768213 38.9567683892 38.95676853021
  1 commentaire
Shree
Shree le 18 Mar 2015
Hello, Thank you for your reply.
You are right. I am getting the actual value when displayed with long format but in the matlab workspace why it still shows the shorter format? Is there any way to see these values in matlab workspace instead of displaying?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by