Create a MATLAB program that creates other programs?

4 次查看(过去 30 天)
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