MATLAB Answers

Problem by using str2double with csv file

9 views (last 30 days)
Ahmed Ghouma
Ahmed Ghouma on 24 Jun 2021
Edited: Stephen on 26 Jun 2021
i have some csv files and i extract some rows from them using readtable (i tried also readmatrix). when i used str2double to the extracted vectors, it gives wrong result ( with e+16 and e+5). Have please anyone help me ?
  6 Comments
Ahmed Ghouma
Ahmed Ghouma on 24 Jun 2021
semicolon is the delimiter ";" and what should be done ?
when i use xlsread it gives NaN

Sign in to comment.

Answers (1)

the cyclist
the cyclist on 24 Jun 2021
Edited: the cyclist on 25 Jun 2021
The issue is that your input file uses commas as the decimal separator, rather than a period ("decimal point"). This means that MATLAB is treating those elements a text rather than numbers.
I did a global replacement of commas for periods, and then your file loads the data as numbers.
T15 = readtable('73_4.csv');
Warning: Column headers from the file were modified to make them valid MATLAB identifiers before creating variable names for the table. The original column headers are saved in the VariableDescriptions property.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table variable names.
output = T15(1:3,2)
output = 3×1 table
Trace1_Gain_Real ________________ -0.00011834 -0.00012968 -0.00017933
I don't think there is a way to change MATLAB's requirement of using a decimal point for input. So, I think that doing the replacement in the input file is your only option. (But I could be wrong.)
  16 Comments
Stephen
Stephen on 26 Jun 2021
"i think in some files it s used commas as the decimal separator, rather than a period ("decimal point") and in some others a decimal point."
I cannot imagine any application or tool randomly alternating between decimal commas and decimal points.
What is more likely is that someone is opening and saving some of the files using Excel, which completely obliterates the original file format. If you want reliable, robust file parsing, avoid saving with MS Excel.
For looking at any text file, including CSV/TSV/SCSV files you should be using a reliable text editor, e.g. notepad++.
In the unlikely event that you really are using an application that really does create files with random decimal separators, you should first try calling
with the delimiter option set to ';' and see if it can correctly identify the decimal separator character.
For example you could simply call delimitedTextImportOptions twice (once with dot, once with comma) and check which one has the desired variable class (double).
If that does not work, you can simply read in a line or two of the file as text and perform your own simple detection algorithm, it would only take a few lines of code.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by