Create a MATLAB program that creates other programs?

조회 수: 4 (최근 30일)
Jeff Ack
Jeff Ack 2016년 6월 14일
편집: Stephen23 2016년 6월 14일
Hi there,
I would like to create 100 MATLAB programs that are identical except for one line of code.
My reason for doing this (rather than including everything in a single program) is because the way my school's server works, I need to submit separate programs in order for them to all run at the same time (each on their own processor).
So, I was wondering if there is a way to create a single MATLAB program which outputs other MATLAB programs (.m files).
Thanks!

채택된 답변

Stephen23
Stephen23 2016년 6월 14일
편집: Stephen23 2016년 6월 14일
Here is one solution. Define two files:
  1. Write a "template" Mfile, which is complete except for that line. On that line put a unique string, such as XXX.
  2. Write another "lines" file, containing every version of that replacement line that you want to use.
Then in a script, do these steps in a loop:
  1. Read one line of the "lines" file, e.g. newline = fgetl(..).
  2. Read the template file into a variable, e.g. str = fileread(..).
  3. Use string functions to find and replace that line, e.g. strrep(str,'XXX',newline).
  4. save the changed variable in a new file (remember it needs a new name).
Bingo! You will have all of your Mfiles /functions, identical except for that one line.
  댓글 수: 2
Jeff Ack
Jeff Ack 2016년 6월 14일
Thanks for the help. I'm completely baffled by the fgetl command. What determines which line of the file it returns? When I input
l_file=fopen('lines.m')
A=fgetl(l_file)
It makes A equal one of the lines of lines.m, but the line changes when I run the function again and I'm not sure how to pick which line it writes to A.
Thanks!
Stephen23
Stephen23 2016년 6월 14일
편집: Stephen23 2016년 6월 14일
As fegtl's help page states, it "returns the next line of the specified file". So the first time it is called it reads the first line, then second time it read the second line, the third time it reads the third line, etc. This makes reading lines of file in a loop very simple, because you can do this (this code is from the help, try it yourself):
fid = fopen(filename);
tline = fgetl(fid);
while ischar(tline)
disp(tline)
tline = fgetl(fid);
end
fclose(fid);
and it will loops over every line in the open file.
"I'm not sure how to pick which line it writes to A" I have no idea what you mean by that, because my answer does not require "picking" any lines: fgetl does that for you. Exactly like I wrote, if you put all of the replacement lines in one file, then fgetl is the perfect way to loop over them. And I have no idea what A is, but if you meant the template file imported as a string, then you also do not need to "pick" any lines, just use strrep.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by