I need to set a file as an input

조회 수: 4 (최근 30일)
Joseph
Joseph 2013년 6월 18일
This is a bit complex. I have a .m file that currently opens a .txt file, edits that file, and saves it under a new name. I currently have the file names for both the file that is opened/edited and the file name that the edited code is saved under hard-coded into my .m file. However, I am going to have to use this program with many different .txt files. I would like to not have to change the .m file's code every time I need to use the program with a different .txt file. Is there anyway I could tell MATLAB which file to open and what to save the edited file as from the command window? So essentially I need to set the old file and new file name as a input variable of sorts in my .m file. I would appreciate any help.
  댓글 수: 1
Matt Kindig
Matt Kindig 2013년 6월 18일
편집: Matt Kindig 2013년 6월 18일
This is actually rather common. Just wrap the file opening, matlab logic, and file saving into a function, i.e.
function out = myfunction(inFile, saveFile)
fid = fopen(inFile, 'rt'); %open your text file for reading
%do matlab stuff here
fid2 = fopen(saveFile, 'wt'); %open save file for writing
fwrite(fid2, ... %or however else you are writing your save file
fclose(fid); fclose(fid2); %close your files.
Then you can just call your function from the command prompt as:
myfunction('myfile1.txt', 'outfile1.txt');
myfunction('myfile2.txt', 'outfile2.txt');
You can even wrap the call to myfunction() in a loop to loop through a bunch of files. See http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F

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

답변 (0개)

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by