Writing a script that writes a script
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hello,
I need to write a program that creates multiple m files with a certain naming scheme that is indexed and inserts lines of code (as strings) into each created file. So far I have:
a = 1:2:60,
for i= 1:length(a)
filename = sprintf('get_settings_00%i', i)
edit(filename)
end
but after the line with "edit(filename)", which creates the different files, I need to somehow print lines within each created file to make a function.
For example, I would like to insert into each file:
function [settings] = get_settings_00%i(settings) \n settings.radius = [%i %i] \n settings.length = settings.radius
where the first %i represents i and the last two i`s represent a and all variables change with each iteration.
Does anyone know how to do this? I am basically writing a scipt that writes another script.
Thanks!
1 comentario
IQBAL
el 27 de Feb. de 2024
cretae and test a MATLAB m-file(script)to create a table of conversions from mph to ft/sec. Allow user to input the 1)start mph value2(endmph value3)increament9filename"mph2fps")Include headers, units and sample output.
Respuestas (2)
Jason Ross
el 10 de Feb. de 2012
You could use something like the following:
out = sprintf([...
'function myout\n' ...
'disp(''hello world'')\n' ...
]);
Then open a file using fopen, then fprintf to write the "out" string to a file and fclose to close it.
This advice comes with all the usual caveats about opening and closing files anywhere (look before you leap (unique filename), check that you did actually write (permissions, disk full) and make sure to clean up (close filehandle))
0 comentarios
Ken Atwell
el 10 de Feb. de 2012
This technique is sometimes called metaprogramming. Jason has good tips. I would also ask how long these scripts need to persist. Will you be calling the scripts days or weeks from now (i.e., in a different MATLAB session), or are they only short-lived. If they will be short-lived, I would be tempted to keep "scripts" in memory and run them with eval:
% Use sprintf to format commands and stick them in a cell array
for a = 1:2:60 get_settings{a} = sprintf('a=%d\n', a); end
% Loop over the cell array and evaluate each command we created above
for a = 1:2:60 eval(get_settings{a}), end
If workable, this would save you the messiness of auto-generating lots of little files you'll want to clean up later.
You could always save get_settings in a MAT if you need to persist these "scripts".
0 comentarios
Ver también
Categorías
Más información sobre Get Started with MATLAB en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!