필터 지우기
필터 지우기

How to import an equation that is user defined in GUI into separate m files?

조회 수: 1 (최근 30일)
Will Sheppard
Will Sheppard 2018년 12월 7일
댓글: Stephen23 2018년 12월 9일
Hi, I am creating a GUI for a project and I want the user to be able to enter an equation. I then want to run a seperate m file with this equation. I have tried global variables to convert it, but it has not been working for me. Thank you

답변 (3개)

Walter Roberson
Walter Roberson 2018년 12월 7일
R2017b or later, use str2sym() and then use matlabFunction() with the 'file' option.
R2017b or earlier use sym() and then use matlabFunction with the 'file' option.

Stephen23
Stephen23 2018년 12월 7일
편집: Stephen23 2018년 12월 7일
Use str2func to generate a nice function handle that you can use/pass to your other code.
Note that you will need to prefix the string with '@(x,y,..)', exactly as if you were defining an anonymous function. For example:
>> str = 'sin(x)+sqrt(y)';
>> fun = str2func(['@(x,y)',str]);
>> fun(pi/2,2)
ans = 2.4142
It is best to avoid global variables, evalin, assignin, and other such bad code practices.
  댓글 수: 2
Will Sheppard
Will Sheppard 2018년 12월 9일
편집: Will Sheppard 2018년 12월 9일
Right now I have this in the main file and it generates the function handle fine, however I do not get how i use this generated function handle in a seperate .m other than manually entering it.Capture.JPG
Stephen23
Stephen23 2018년 12월 9일
"however I do not get how i use this generated function handle in a seperate .m ..."
A function is just a variable in the workspace. You can pass it to a function, just like any other variable.
"...other than manually entering it."
It is not clear what you mean. You do not describe what you tried or what you expect to happen.
Of course you will have to specify where you want to use this function handle: it will not just magically jumpy from where you define it to inside the function where you want to use it. In any case, the simplest, easiest, and most efficient way to pass that function handle to your function is to ensure that your function is written to accept it as an input argument:
fun = str2func(y_in);
yourOtherFun(fun)

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


Arvind Sathyanarayanan
Arvind Sathyanarayanan 2018년 12월 7일
편집: Arvind Sathyanarayanan 2018년 12월 7일
Is your m-file a function? If yes, you can pass the variable containing your equation as input argument. You could also send the variable with the equation to the base workspace using the assigin command and evalin the variable into your m-file/function

카테고리

Help CenterFile Exchange에서 Function Handles에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by