2
votes

I have several text files that are formatted something like this, each file with a different number of rows (but around 1000 rows in each).

  Id                   X                   Y                    Curve
   1        0.0000000000       -0.0000286102               Domain_BCs
   2        0.0010000000     -202.5294952393               Domain_BCs
   3        0.2028919513    -1098.9577636719               Domain_BCs
   4        1.0000000000    -2286.1757812500               Domain_BCs

I want to bring this data into Matlab, break it into separate vectors according to the string in the Curve column, and plot Y as a function of X.

The data is space-delimited with a variable number of spaces, and there are also a variable number of spaces at the start of each row (before the Id column). I know that readtable would work if there were no spaces at the beginning of the rows and only one space between columns. Is there any way to make readtable work with data in this format?

I also considered using textscan, but my understanding is that I would need to know the number of rows in order to use textscan, which makes things trickier because the number of rows is different for each file I want to process.

2
You can just use textscan. Please see my answer. - EJG89

2 Answers

2
votes

Textscan is exactly meant for this purpose. You can just use textscan without knowing the number of lines :) Any amount of whitespace is interpreted as a single delimiter standard. So just use:

FID = fopen('test2.txt');

formatSpec = '%d %f %f %s';

C = textscan(FID,formatSpec);

fclose(FID)

In test2.txt I just pasted your example a few times (without headers).

Each column of your file is then read into a cell in C.

Soruce: http://www.mathworks.nl/help/matlab/ref/textscan.html

0
votes

fgets - Read lines without concerning number of lines

strsplit - split a string with delimiters

fid = fopen('yourfile.txt');

tline = fgets(fid);
while ischar(tline)
    trow = strsplit(tline, ' ', 'CollapseDelimiters',true);
    tline = fgets(fid);
end

fclose(fid);

If you want to speed up a little bit,

fid = fopen('yourfile.txt');

counter = 0;
tline = fgets(fid);
trow = strsplit(tline, ' ', 'CollapseDelimiters',true);
while ischar(tline)
    counter = counter + 1;
    tline = fgets(fid);
end
T = zeros(counter, length(trow));

frewind(fid);

while ischar(tline)
    trow = strsplit(tline, ' ', 'CollapseDelimiters',true);
    tline = fgets(fid);
end

fclose(fid);