read value from an external file .txt

2 visualizaciones (últimos 30 días)
Scacchio
Scacchio el 10 de Feb. de 2023
Comentada: Walter Roberson el 10 de Feb. de 2023
I have an external file to read in Matlab with *.txt format and I need to save the value of each zone in an array dataread to plot.
For example the file read.txt have this data:
Results:
Zone 2 : 4,565e-0022
Zone 3 : 4,565e-0022
Zone 4 : 4.565e-0022
Zone 5 : 4.565e-0022
total: 5464.002e-2
I try to use the script but it does not work. How can i solve it?
data=fopen('read.txt','r')
tline=fgets(data); % to read the next line
for i=2:(end(data)-1)
dataread=fscanf(data,'<Zone 'num2str(i) ' :> %f',[2,inf]);
end
also, for some decimal values commas are used for others points, how can I standardize?
  3 comentarios
Walter Roberson
Walter Roberson el 10 de Feb. de 2023
2 inf expects at least two values but dataread(i) is a scalar output location.
Scacchio
Scacchio el 10 de Feb. de 2023
File attached

Iniciar sesión para comentar.

Respuestas (1)

Rik
Rik el 10 de Feb. de 2023
You can do it with fscanf, but it you get a lot more flexibility if you use a regular expression instead. If you want to use this code on an older release: my readfile function will read a text file to a cellstr, just like the first line below does.
data=cellstr(readlines('read.txt'));
T=regexp(data,'Zone\s*\d\s*:\s*(\d*[,\.]?\d*[eE]?[-+]?\d*)','tokens');
T=[T{:}];T=[T{:}]
T = 1×4 cell array
{'4.565e-0022'} {'3.555e-0022'} {'1.132e+0022'} {'4.565e-0022'}
dataread=str2double(T)
dataread = 1×4
1.0e+22 * 0.0000 0.0000 1.1320 0.0000
You don't see much here, because the third is e+22 and the rest is e-22
  1 comentario
Walter Roberson
Walter Roberson el 10 de Feb. de 2023
Using 4-digit numbers for exponents is pretty strange. It does have meaning if you are using Intel 80 bit floating point numbers, but those are designed to be for internal use only and are not intended to make it to end-users

Iniciar sesión para comentar.

Categorías

Más información sobre String Parsing en Help Center y File Exchange.

Productos


Versión

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by