Reading values from a text file and converting to array.

I have a text file 'U.txt' which has data as follows:
# x 0 0.3 0.4
# y 0 0 0
# z 0 0 0
# Time
0.000125 (0.101993 0 0) (0.100009 0 0) (0.100009 0 0)
0.00025 (0.14199 0 0) (0.0998676 0 0) (0.0976896 0 0)
0.000375 (0.161106 0 0) (0.0989464 0 0) (0.0895835 0 0)
0.0005 (0.178717 0 0) (0.0960872 0 0) (0.0763535 0 0)
I want to extract the values of each column (without the header) into respective arrays.example:
Array1= 0.000125 0.00025 0.000375 0.0005
Array2= 0.101993 0.14199 0.161106 0.178717
Array3= 0.100009 0.0998676 0.0989464 0.096872
Array4= 0.100009 0.0976896 0.0895835 0.0763535
Kindly help me out. Thanks in advance

 Respuesta aceptada

Cedric
Cedric el 28 de Mayo de 2014
Editada: Cedric el 28 de Mayo de 2014
Here is one way to achieve what you want to do:
>> content = fileread( 'myFile.txt' ) ;
>> data = textscan( content, '%f (%f %*d%*d) (%f %*d%*d) (%f%*[^\n]', ...
'HeaderLines', 4 ) ;
where columns are stored into cells of cell array data:
>> data
data =
[4x1 double] [4x1 double] [4x1 double] [4x1 double]
>> data{1}
ans =
1.0e-03 *
0.1250
0.2500
0.3750
0.5000
>> data{2}
ans =
0.1020
0.1420
0.1611
0.1787
>> data{3}
ans =
0.1000
0.0999
0.0989
0.0961
>> data{4}
ans =
0.1000
0.0977
0.0896
0.0764

3 comentarios

Thank you very much! Its working. but, how can I make the numbers more accurate? Precision To a greater number of digits?
It is very accurate. It just was not showing in the command window when printed. Thanks!
Yes, the default display format is short, which rounds variables content when displayed in the command window. If you really want to see variables' content in higher precision, you can execute
>> format long

Iniciar sesión para comentar.

Preguntada:

el 28 de Mayo de 2014

Respondida:

el 11 de Jun. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by