Question

I am trying to read data into Matlab consisting of rows of numbers and texts however I only want to read the numerical values and skip the text (whenever it occurs). I have been using textscan but to read the numbers in but when it reaches a column with text the functions terminates.

This is my first post so I am not familiar with how to post my data and code here so I have attached a bit of the data below:

0.37364   1.318    0.1090E-02    0.4885E-03    0.236E-02    0.527E-02
0.39237   1.372    0.1214E-02    0.5470E-03    0.211E-02    0.546E-02
0.41129   1.580    0.1612E-02    0.6992E-03    0.142E-02    0.588E-02
 CF SET TO 0.000002 AT X=      0.430 ON SURFACE  1 (1=U/S, 2=L/S)
0.43038   3.070    0.4482E-02    0.1160E-02    0.200E-05    0.905E-02
 HBAR MAX LIMIT REACHED

So I want Matlab to read the columns with the numerical data and skip the ones containing the text.

I appreciate your help and thank you in advance!!!

Hamza

Was it helpful?

Solution

Solution

result = [];

fid=fopen('data.txt');
while 1
    tline = fgetl(fid);
    if ~ischar(tline), break, end
    celldata = textscan(tline,'%f %f %f %f %f %f');
    matdata = cell2mat(celldata);
    % match fails for text lines, textscan returns empty cells
    result = [result ; matdata];
end

fclose(fid);

Result

result =
0.3736    1.3180    0.0011    0.0005    0.0024    0.0053
0.3924    1.3720    0.0012    0.0005    0.0021    0.0055
0.4113    1.5800    0.0016    0.0007    0.0014    0.0059
0.4304    3.0700    0.0045    0.0012    0.0000    0.0091

data.txt

0.37364   1.318    0.1090E-02    0.4885E-03    0.236E-02    0.527E-02
0.39237   1.372    0.1214E-02    0.5470E-03    0.211E-02    0.546E-02
0.41129   1.580    0.1612E-02    0.6992E-03    0.142E-02    0.588E-02
 CF SET TO 0.000002 AT X=      0.430 ON SURFACE  1 (1=U/S, 2=L/S)
0.43038   3.070    0.4482E-02    0.1160E-02    0.200E-05    0.905E-02
 HBAR MAX LIMIT REACHED

OTHER TIPS

I came up with the following work-around:

    m=1;
    for k=1:10;    % create for loop ranging from start to finish of data
        ful = sscanf(S{k,1},'%f');  % scan each line for a floating point number
        le=size(ful);               % gives size of the scanned values

        if le(1) > 0                % Only read if there is a value of > 0 ( for non-floating i.e. string, the value = 0)
            for t=1:le(1)
                data1(m,t)=ful(t);  % store the value in matrix
            end
            m=m+1;
        end
    end

This seems to do the trick!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top