MATLAB Answers

How to insert data with fopen ?

3 ビュー (過去 30 日間)
MarineM
MarineM 2021 年 6 月 11 日
回答済み: Jan 2021 年 6 月 11 日
Hi, I was wondering how to put my own data with fopen in a file that I created?
ftempd = fopen('tempd.r2c','w'); %creation of file .r2c
fprintf(ftempd,'%d/n',round(tempd)); % matrix 32x32 ???
fclose(ftempd);
Knowing that < tempd > are data 32x32 that I want to insert into my file tempd.r2c
I want to create a matrix with my data into my file to have all my 32x32 data, something like that but I need 32x32 : (see the pic or the exemple) :
:Frame 1 1 "2002/01/01 07:00:00.000"
261.90 261.43 260.50 258.93 257.52
259.31 258.68 258.32 258.11 257.80
257.90 257.92 257.64 257.36 257.46
258.18 257.89 257.27 257.06 256.89
258.43 258.11 257.41 257.07 257.40
258.69 258.44 258.14 258.27 258.72
258.96 258.77 258.81 259.10 259.27
I need the exact same frame with 2 digits after the point.
I hope someone can help me, thank you :)

回答 (3 件)

Walter Roberson
Walter Roberson 2021 年 6 月 11 日
fopen() by itself can never be used to write data to a file. It can be used in some cases to remove all data from a file.
The file i/o operations that follow after fopen() can never be used to insert data into the middle of a file, moving the remaining data. They can be used to read from a file, append to the end of a file, and in some cases to overwrite the middle of a file with exactly the same size data.
If you want to insert something, moving what remains to further on, then it becomes necessary to rewrite the entire rest of the file.
In most cases, it is safer to instead create a new file, copy from the old to the new until the insertion point, then write in the new data, and then copy the rest of the old to the new. This way if there is any problem with the process then the old file will still be there to allow you fix the bugs and try again.

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021 年 6 月 11 日
THis is how you can export data from MATLAB into an external file:
FID =fopen('MYData.dat', 'w');
STR =':Frame 1 1 "2002/01/01 07:00:00.000';
fprintf(FID, '%50s \n', STR);
fprintf(FID, '%3.2f %3.2f %3.2f %3.2f %3.2f \n', DATA); % Only your numerical data
fclose(FID)

Jan
Jan 2021 年 6 月 11 日
fmt = [repmat('%.2f ', 1, 32). '\n'];
ftempd = fopen('tempd.r2c', 'w');
fprintf(ftempd, fmt, tempd.');
fclose(ftempd);

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by