How to run a script name inputed by the user within a script.

10 ビュー (過去 30 日間)
james
james 2012 年 4 月 9 日
So, I have a script that I want to use to enter variables from an .m file that the user enters.
So, I have
filename=input('Please enter the filename:');
But I want to then run the entered script within the script. Any idea how to do this? I know if I already knew the name of the script I could just put it directly in the script, but I don't know how to do it this way. Thanks.

採用された回答

Sean de Wolski
Sean de Wolski 2012 年 4 月 9 日
  2 件のコメント
james
james 2012 年 4 月 9 日
If I store the name of the file in "filename" and then type
run filename
It will attempt to execute a script named filename, and not the string that's stored in the input.
Walter Roberson
Walter Roberson 2012 年 4 月 9 日
run(filename)

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

その他の回答 (2 件)

Daniel Shub
Daniel Shub 2012 年 4 月 9 日
There is the run function
doc run
  2 件のコメント
james
james 2012 年 4 月 9 日
If I store the name of the file in "filename" and then type
run filename
It will attempt to execute a script named filename, and not the string that's stored in the input. How do I fix this?
Image Analyst
Image Analyst 2012 年 4 月 9 日
Yes, running something with the command style is different than running it with the function style. With command style, no parentheses are used and it thinks that what you have there is the string itself except without the single quotes around it, so that's why it tried to run a script called "filename.m". With the function style, you pass in a variable and no quotes and it runs it assuming you made the variable with single quotes:
filename = 'c:/blah/foo.m';
run(filename);
So, bottom line, you should use parentheses and then your existing code should work correctly.

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


Alan
Alan 2012 年 4 月 9 日
use the 'eval' function
  2 件のコメント
Daniel Shub
Daniel Shub 2012 年 4 月 10 日
While I don't like to bash solutions that work, I find this solution to be miserable. Yes, the run function, as suggested by Sean and myself, eventually uses eval, but there is a difference. The run function makes sure that the script is actually a file and not some arbitrary code.
Walter Roberson
Walter Roberson 2012 年 4 月 10 日
I agree, run(filename) is much better.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by