Create and write t an .m file from MATLAB script

조회 수: 78 (최근 30일)
Enrico
Enrico 2014년 2월 6일
답변: Friedrich 2014년 2월 6일
Hi,
I would like to execute the following steps from a script:
  1. Create an .m file
  2. Write a string in the file
  3. Save and Close file
This is as far as I have gotten:
a='test string';
edit file.m
FID=fopen('file.m');
fprintf(FID, '%s', a);
fclose(FID);
These lines do not return an error. The file is generated in the current directory and opens in the editor, however no string is written to file and the file does not close.
Any ideas?
Thank You very much!

채택된 답변

Friedrich
Friedrich 2014년 2월 6일
Hi,
take a look at the documentation for fopen, it states:
"fileID = fopen(filename) opensthe file, filename, for binary read access,..."
Since you want to write you need to pass down an additional argument. Depending on what you like to do I guess either 'a' or 'w' is what you are looking. If you call
FID = fopen('file.m','a')
You would open or create new file for writing. Append data to theend of the file.
When you call
FID = fopen('file.m','w')
you would ppen or create new file for writing. Discard existing contents, if any.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT-Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by