0

I have been trying in vain for days to do one seemingly simple thing--I want to read data from a .txt file that looks like this:

    0.221351321
    0.151351321
    0.235165165
    8.2254546 E-7

into Matlab. I've been able to load the data in the .txt file as a column vector using the fscanf command, like so:

    U=fscanf(FileID, '%e')

provided that I go through the file first and remove the space before the 'E' wherever scientific notation occurs in the data set.

Since I have to generate a large number of such sets, it would be impractical to have to do a search-and-replace for every .txt file.

Is there a way for matlab to read the data as it appears, as in the above example (with the space preceding 'E'), and put it into a column vector?

For anyone who knows PARI-GP, an alternate fix would be to have the output devoid of spaces in the first place--but so far I haven't found a way to erase the space before 'E' in scientific notation, and I can't predict if a number in scientific notation will appear or not in the data set.

Thank you!

P. Gillich
  • 289
  • 1
  • 9

3 Answers3

1

Thank you all for your help, I have found a solution. There is a way to eliminate the space from PARI-GP, so that the output .txt file has no spaces to begin with. I had the output set to "prettymatrix". One needs to enter the following:

    ? \o{0}

to change the output to "Raw," which eliminates the space before the "E" in scientific notation.

Thanks again for your help.

P. Gillich
  • 289
  • 1
  • 9
0

A simple way, may not be the best, is to read line by line, remove the space and convert back to floating point number.

For example,

x = []
tline = fgetl(FileID);
while ischar(tline)
    x = [x str2num(tline(find(~isspace(tline))))]
    tline = fgetl(FileID);
end
Jerry Chou
  • 302
  • 1
  • 11
0

One liner:

data = str2double(strsplit(strrep(fileread('filename.txt'),' ',''), '\n'));

strrep removes all the spaces, strsplit takes each line as a separate string, and str2double coverts the strings to numbers.

Vahe Tshitoyan
  • 1,439
  • 1
  • 11
  • 21