Search code examples
matlabtextscan

Matlab:Reading textfile into matrix


I want to read data from a text file in Matlab. The file describes a surface consists of two parts: 1)A header with information on x,y dimensions in pixels and nm etc. 2)Matrix with height values (512x512)

When I try to read just the matrix first I end up with a single column vector instead of a matrix C = textscan(id,'%f','HeaderLines',18,'Delimiter','\t') The file contains " " seperated values and the lines seperated the rows of the matrix. It works when I manually delete the header and read it with A=dlmread(path,'\t',[0 0 511 511]);

I want to obtain the same 512x512 matrix with textscan so that I can later also parse the header - how can I do that?


Solution

  • If you are not strictly bound to textscan, you may use fscanf instead (see docs). Like this:

    fid = fopen('FileName.txt');
    
    % here you have to skip (or parse) your header lines
    % and determine number of rows/columns in your data matrix
    
    A = fscanf(fid, '%g', [NColumns NRows]);
    fclose(fid);
    
    % Transpose so that A matches
    % the orientation of the file
    A = A';
    

    UPDATE1

    This code might be not very elegant, but it will parse your header into FileInfo structure so you may use the data later in your code.

    % sample file header
    %
    % # File Format = ASCII
    % # Created by SPIP 6.2.8.0 2014-08-15 20:41
    % # Original file: D:\...
    % # x-pixels = 512
    % # y-pixels = 512
    % # x-length = 319375
    % # y-length = 319375
    % # x-offset = 0
    % # y-offset = 0
    % # z-unit = [nm]
    % # scanspeed = 638.75
    % # forcecurve = 0
    % # voidpixels =76
    % # description =62:Confocal Height Image  Date: 2013-08-20T13:36 User: Unknown
    % # Start of Data: MATRIX
    
    fid = fopen('text.txt','r');
    
    FileInfo  = [];
    tmpString = '';   % initializing the s
    while isempty(strfind(tmpString,'Start of Data: MATRIX'))
    
        % we read a string from file
        tmpString = fgetl(fid);
        % and split it into left and right parts according to the '=' position
        [kev,val] = strtok( tmpString(3:end) , ':=' );
    
        % remove spaces from key name and make it a valid variable name in MatLab
        keyName = genvarname( strrep(strrep(kev,'-',''),' ','') );
    
        % check if key value is a number
        [x,OK]    = str2num(strtrim(val(2:end)));
    
        % if value is a number, use it otherwise leave the trimmed original string
        if OK
            FileInfo.(keyName) = x;
        else
            FileInfo.(keyName) = strtrim(val(2:end));
        end
    
    end
    
    % Now we can read the data
    A = fscanf(fid, '%g', [FileInfo.xpixels FileInfo.ypixels]);
    fclose(fid);
    
    % Transpose so that A matches
    % the orientation of the file
    %A = A';