在Matlab中为.dat文件指定小数点分隔符 [英] Specify decimal separator for .dat file in matlab
问题描述
我有一堆.dat文件,其中的小数点分隔符是逗号而不是点. MATLAB中是否有任何函数将逗号设置为分隔符?
I've got a bunch of .dat files, where the decimal separator is comma instead of dot. Is there any function in MATLAB to set comma as the separator?
推荐答案
您将必须以文本形式读取数据(使用textscan
,textread
,dlmread
,
You will have to read the data in as text (with textscan
, textread
, dlmread
, etc.) and convert to numeric.
假设您已将数据读取到单元格数组中,并且每个单元格中的每个数字都是如此:
Say you have read the data into a cell array with each number in a cell:
>> C = {'1,2345','3,14159','2,7183','1,4142','0,7071'}
C =
'1,2345' '3,14159' '2,7183' '1,4142' '0,7071'
按以下方式使用strrep
和str2double
:
>> x = str2double(strrep(C,',','.'))
x =
1.2345 3.1416 2.7183 1.4142 0.7071
对于来自注释的示例数据,您有一个文件"1.dat",其格式类似于:
For your example data from comments, you have a file "1.dat" formatted similarly to:
1,2 3,4
5,6 7,8
在这里您有一个空格作为定界符.默认情况下,textscan
使用空格作为分隔符,这样就可以了.您只需在下面做的就是更改数据列数的格式说明符,方法是对每列重复%s
(例如,在这里我们需要对两列使用'%s%s'
):
Here you have a space as a delimiter. By default, textscan
uses whitespace as a delimiter, so that is fine. All you need to change below is the format specifier for the number of columns in your data by repeating %s
for each column (e.g. 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);
textscan
的输出是由空格分隔的每一列的单元格数组.将这些列合并为一个单元格数组,然后运行命令以将其转换为数字:
The output of textscan
is a cell array for each column delimited by whitespace. Combine the columns into a single cell array 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
这篇关于在Matlab中为.dat文件指定小数点分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!