read each line a text file using Matlab function

조회 수: 2 (최근 30일)
nadia naji
nadia naji 2021년 4월 21일
댓글: nadia naji 2021년 4월 21일
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.

채택된 답변

Stephen23
Stephen23 2021년 4월 21일
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
nadia naji
nadia naji 2021년 4월 21일
thank you very much for your fast and accurate help;)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by