skip reading headers in MATLAB

前端 未结 2 1072
旧时难觅i
旧时难觅i 2020-12-19 20:18

I had a similar question. but what i am trying now is to read files in .txt format into MATLAB. My problem is with the headers. Many times due to errors the system rewrites

2条回答
  •  不知归路
    2020-12-19 20:51

    It turns out that you can still use textscan. Except that you read everything as string. Then, you attempt to convert to double. 'str2double' returns NaN for strings, and since headers are all strings, you can identify header rows as rows with all NaNs.

    For example:

    %# find and open file
    [c,pathc]=uigetfile({'*.txt'},'Select the data','V:\data'); 
    file=[pathc c];
    fid = fopen(file);
    
    %# read all text
    strData = textscan(fid,'%s%s%s%s%s%s','Delimiter',','); 
    
    %# close the file again
    fclose(fid);
    
    %# catenate, b/c textscan returns a column of cells for each column in the data
    strData = cat(2,strData{:}); 
    
    %# convert cols 3:6 to double
    doubleData = str2double(strData(:,3:end));
    
    %# find header rows. headerRows is a logical array
    headerRowsL = all(isnan(doubleData),2);
    
    %# since I guess you know what the headers are, you can just remove the header rows
    dateAndTimeCell = strData(~headerRowsL,1:2);
    dataArray = doubleData(~headerRowsL,:);
    
    %# and you're ready to start working with your data 
    

提交回复
热议问题