How can open and read .dat file?

A=[3 4 4 NaN NaN NaN NaN NaN;
36 46 4 4 1 3 NaN NaN;
24 32 3 3 1 3 2 3;
25 32 3 3 1 3 2 NaN];
I have stored this matrix as a .dat file using following code:
filename = sprintf('output.dat');
dlmwrite(filename, A, ' ' );
Now I want to open (fopen) this "output.dat" file in read mode and want to read data from this open file using fscanf. How can I do that?
any help would be greatly appreciated.
Thank you!

댓글 수: 2

Rik
Rik 2020년 9월 8일
What did you try?
The matrix A has been stored in output.dat file in my computer. Now I want to read data from the output.dat file using fopen and fscanf. I have used the following code:
fileID = fopen('output.dat','r');
result = fscanf(fileID,'%f')
It results single column array but I need the output in the following format:
result=[3 4 4 NaN NaN NaN NaN NaN;
36 46 4 4 1 3 NaN NaN;
24 32 3 3 1 3 2 3;
25 32 3 3 1 3 2 NaN];
or,
result=result={[3 4 4]; [36 46 4 4 1 3]; [24 32 3 3 1 3 2 3]; [25 32 3 3 1 3 2]};

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

답변 (1개)

Walter Roberson
Walter Roberson 2020년 9월 8일

0 개 추천

result = load('output.dat');

댓글 수: 4

SM
SM 2020년 9월 9일
Appreciated! but I want in different way. I have explained in my comment about how I have tried to solve it. Could you proceed that way?
Walter Roberson
Walter Roberson 2020년 9월 9일
You cannot solve the problem using fscanf() unless you already know the number of columns in advance.
You can solve the problem by looking with fgets() or fgetl() to pull in one line at a time, and sscanf() that line, and check the lines for consistency of lengths.
You can also solve the problem with dlmread() or with textscan(). If you use textscan then you can pass in '' (empty string) as the format, which is an undocumented option that will figure out how many columns there are for numeric use.
You can also use readmatrix() for R2019b or later.
Huy Le Van
Huy Le Van 2020년 11월 4일
편집: Rik 2020년 11월 4일
I can not read file.dat.
Do you replay follow email []@gamil.com
Walter Roberson
Walter Roberson 2020년 11월 4일
dat is not a fixed file format. It is used by many different programs for whatever data they have handy. You would need to know which program created the file to try to figure out what the file format is.

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

카테고리

도움말 센터File Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

태그

질문:

SM
2020년 9월 8일

댓글:

2020년 11월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by