Matlab: How to read in numbers with a comma as decimal separator?

前端 未结 4 1569
礼貌的吻别
礼貌的吻别 2020-12-03 23:47

I have a whole lot (hundreds of thousands) of rather large (>0.5MB) files, where data are numerical, but with a comma as decimal separator. It\'s impractical for me to use a

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 00:25

    My solution (assumes commas are only used as decimal place holders and that white space delineates columns):

    fid = fopen("FILENAME");
    indat = fread(fid, '*char');
    fclose(fid);
    indat = strrep(indat, ',', '.');
    [colA, colB] = strread(indat, '%f %f');
    

    If you should happen to need to remove a single header line, as I did, then this should work:

    fid = fopen("FILENAME");                  %Open file
    indat = fread(fid, '*char');              %Read in the entire file as characters
    fclose(fid);                              %Close file
    indat = strrep(indat, ',', '.');          %Replace commas with periods
    endheader=strfind(indat,13);              %Find first newline
    indat=indat(endheader+1:size(indat,2));   %Extract all characters after first new line
    [colA, colB] = strread(indat, '%f %f');   %Convert string to numerical data
    

提交回复
热议问题