How to run m-file from another m-file by input string

2 ビュー (過去 30 日間)
Arief Anbiya
Arief Anbiya 2014 年 7 月 16 日
コメント済み: Arief Anbiya 2014 年 7 月 17 日
I have tried this code below trying to immediately run an m-file that was just created in another m-file :
savename = input('name : ');
f=fopen(savename,'w');
%%%writes in the created m-file
fclose(f);
run(save_name);
The above code neither produce any error or runs the script. Any comments? thanks.
  2 件のコメント
Geoff Hayes
Geoff Hayes 2014 年 7 月 16 日
編集済み: Geoff Hayes 2014 年 7 月 16 日
I was able to do something similar but had to change your code slightly
% use 's' to indicate that the result is a string and not an
% expression that should not be evaluated
savename = input('name : ', 's');
% open the file
f=fopen(savename,'w');
% write a line to print out a statement
fprintf(f,'fprintf(''this is a test\\n'');');
% close the file
fclose(f);
% use savename rather than save_name
run(save name);
And this worked fine with the output being
this is a test
and the input being test.m.
What are you writing to your m file? If you run this script from the Command Window, does it work or does it only fail when you try to call it from the other m file (as above)?
Arief Anbiya
Arief Anbiya 2014 年 7 月 17 日
Thanks @Geoff, it worked.. I just realized that my code actually worked (without the typo). I write variables in the created m-file, so I was looking for those variables to appear in the workspace, then i realized Matlab doesnt do that.

サインインしてコメントする。

採用された回答

Alfonso Nieto-Castanon
Alfonso Nieto-Castanon 2014 年 7 月 16 日
編集済み: Alfonso Nieto-Castanon 2014 年 7 月 16 日
try this:
...
fclose(f);
rehash;
run(save_name);
also make sure that your variable save_name does not include the extension .m, while the file that you create does include it. So that would be something like:
savename = 'test';
f = fopen([savename '.m'],'wt');
...
fclose(f);
rehash;
run(savename);
  2 件のコメント
Geoff Hayes
Geoff Hayes 2014 年 7 月 16 日
Why can't the script name have the extension .m? The example at run allows for it.
Alfonso Nieto-Castanon
Alfonso Nieto-Castanon 2014 年 7 月 16 日
Interesting (and thanks for pointing this out)... Entering a script name with the extension .m (and without a filepath) produces an error on an old version of Matlab (R2008b), but it seems to work just fine on a more recent version (R2013a)...

サインインしてコメントする。

その他の回答 (1 件)

David Sanchez
David Sanchez 2014 年 7 月 16 日
I do that some times just by doing this:
another_script = input('script name: ','s'); % and type the name of your other script
run(another_script);
with no need of either fopen or fclose
  1 件のコメント
Geoff Hayes
Geoff Hayes 2014 年 7 月 16 日
Arief's code is creating a script from within another, and so needs the fopen and fclose.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeOrange についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by