Can you have the user input an equation in MATLAB?

조회 수: 7 (최근 30일)
lbon jbn
lbon jbn 2011년 11월 26일
I know I've been posting quite a few questions here but my MATLAB final is due in several days and I'm trying to make sure my program is going to be good. IO'm just wondering if it's possible for a user to input an equation? For example in the volume calculator I am working on I would like to have the user define a set of variables and then input an equation consisting of those variables and of course have matlab solve the equation. If this is possible what would be the code? I have snooped around online for a bit and have not found it.

답변 (3개)

Daniel Shub
Daniel Shub 2011년 11월 26일
There are a number of ways of doing this ... I think they all involve eval, which makes them problematic. Assuming you have a string str with the function that you want to evaluate, the simplest, but worst answer is:
x = eval(str);
I think I would do something like:
f = function_handle.empty; % I think this helps mlint with the eval
f = eval(['@()', str]);
x = f(); % Note the () is important
This limits the problems that the eval can cause.

Walter Roberson
Walter Roberson 2011년 11월 26일
If you have a new enough version, an explicit eval is not needed to create an anonymous function.
Some people use the older inline() instead of an anonymous function.
Equations can also be evaluated by using the facilities of the symbolic toolbox.
  댓글 수: 1
Daniel Shub
Daniel Shub 2011년 11월 28일
I cannot get inline or str2func to work for the case where "the user defines a set of variables". I take this to mean something like: x = 1; y = 2; and you want f = x+y = 3.

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


lbon jbn
lbon jbn 2011년 11월 27일
Awesome, thank you guys, I got it to work!

카테고리

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

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by