Specify decimal separator for .dat file in matlab

I have a bunch of .dat files where the decimal separator is a comma, not a period. Is there any function in MATLAB to set the comma as a separator?

+1
source share
1 answer

You will need to read the data as text (with textscan , textread , dlmread , etc. ) and convert to numeric.

Say you read the data in an array of cells with each number in the cell:

 >> C = {'1,2345','3,14159','2,7183','1,4142','0,7071'} C = '1,2345' '3,14159' '2,7183' '1,4142' '0,7071' 

Use strrep and str2double as follows:

 >> x = str2double(strrep(C,',','.')) x = 1.2345 3.1416 2.7183 1.4142 0.7071 

For your example data from the comments, you have the file "1.dat", formatted similarly:

 1,2 3,4 5,6 7,8 

Here you have a space as a separator. By default, textscan uses a space as a delimiter, so this is normal. All you need to change below is a format specifier for the number of columns in your data, repeating %s for each column (for example, here we need '%s%s' for two columns):

 >> fid = fopen('1.dat','r'); >> C = textscan(fid,'%s%s') C = {2x1 cell} {2x1 cell} >> fclose(fid); 

The output of textscan is an array of cells for each column marked with a space. Combine the columns into a single array of cells and run the commands to convert to numeric:

 >> C = [C{:}] C = '1,2' '3,4' '5,6' '7,8' >> x = str2double(strrep(C,',','.')) x = 1.2000 3.4000 5.6000 7.8000 
+1
source

Source: https://habr.com/ru/post/1382170/


All Articles