read each line a text file using Matlab function

4 visualizaciones (últimos 30 días)
nadia naji
nadia naji el 21 de Abr. de 2021
Respondida: Mathieu NOE el 21 de Abr. de 2021
I have a text file that each line of it is as follows:
n:1 mse_avg:8.46 mse_y:12.69 mse_u:0.00 mse_v:0.00 psnr_avg:38.86 psnr_y:37.10 psnr_u:inf psnr_v:inf
n:2 mse_avg:12.20 mse_y:18.30 mse_u:0.00 mse_v:0.00 psnr_avg:37.27 psnr_y:35.51 psnr_u:inf psnr_v:inf
n:3 mse_avg:10.89 mse_y:16.33 mse_u:0.00 mse_v:0.00 psnr_avg:37.76 psnr_y:36.00 psnr_u:inf psnr_v:inf
n:4 mse_avg:12.45 mse_y:18.67 mse_u:0.00 mse_v:0.00 psnr_avg:37.18 psnr_y:35.42 psnr_u:inf psnr_v:inf
I need to read each line in a separate line and I use `readvars` matlab function, but the output is only `n` as follow
n
n
n
n
and it cannot extract other variables. do you know what is the problem? does Matlab have any other functions for reading a text file?

Respuestas (1)

Mathieu NOE
Mathieu NOE el 21 de Abr. de 2021
hello Nadia
if you use readvars, you have to know / specify how many variables you want to output
example , if I specify only 2 variables in the output : (I saved your data in a txt file )
[Var1,Var2] = readvars('test2.txt')
will give me
Var1 = 4×1 cell array
{'n'}
{'n'}
{'n'}
{'n'}
Var2 = 4×1 cell array
{'1 mse_avg'}
{'2 mse_avg'}
{'3 mse_avg'}
{'4 mse_avg'}
Another alternative to get the entire data as table
opts = detectImportOptions('test2.txt');
data = preview('test2.txt',opts)
but I wonder if the way the data has been splitted ( delimiter = : ) is the way you wanted it ?
data =
4×10 table
Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10
_____ _____________ _______________ _______________ ______________ _________________ ________________ ________________ ______________ _____
{'n'} {'1 mse_avg'} {'8.46 mse_y' } {'12.69 mse_u'} {'0.00 mse_v'} {'0.00 psnr_avg'} {'38.86 psnr_y'} {'37.10 psnr_u'} {'inf psnr_v'} Inf
{'n'} {'2 mse_avg'} {'12.20 mse_y'} {'18.30 mse_u'} {'0.00 mse_v'} {'0.00 psnr_avg'} {'37.27 psnr_y'} {'35.51 psnr_u'} {'inf psnr_v'} Inf
{'n'} {'3 mse_avg'} {'10.89 mse_y'} {'16.33 mse_u'} {'0.00 mse_v'} {'0.00 psnr_avg'} {'37.76 psnr_y'} {'36.00 psnr_u'} {'inf psnr_v'} Inf
{'n'} {'4 mse_avg'} {'12.45 mse_y'} {'18.67 mse_u'} {'0.00 mse_v'} {'0.00 psnr_avg'} {'37.18 psnr_y'} {'35.42 psnr_u'} {'inf psnr_v'} Inf

Community Treasure Hunt

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

Start Hunting!

Translated by