MATLAB Answers

read each line a text file using Matlab function

1 view (last 30 days)
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? I need to extract psnr_y from each line, for this aim I wan to extract each line in differen variables such as readvars function's output.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 21 Apr 2021
opt = {'Delimiter',{':',' '}};
fid = fopen('data.txt','rt');
nmc = nnz(fgetl(fid)==':');
frewind(fid);
fmt = repmat('%s%f',1,nmc);
tmp = textscan(fid,fmt,opt{:});
fclose(fid);
fnm = [tmp{:,1:2:end}];
out = cell2struct(tmp(:,2:2:end),fnm(1,:),2)
out = struct with fields:
n: [4×1 double] mse_avg: [4×1 double] mse_y: [4×1 double] mse_u: [4×1 double] mse_v: [4×1 double] psnr_avg: [4×1 double] psnr_y: [4×1 double] psnr_u: [4×1 double] psnr_v: [4×1 double]
out.n
ans = 4×1
1 2 3 4
out.psnr_y
ans = 4×1
37.1000 35.5100 36.0000 35.4200
  1 Comment
nadia naji
nadia naji on 21 Apr 2021
thank you very much for your fast and accurate help;)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!