简体   繁体   English

如何在MATLAB中查找函数的值?

[英]How to find a value of a function in MATLAB?

I just started using MATLAB, and for that I am not familiar with MATLAB itself. 我刚刚开始使用MATLAB,因此我并不熟悉MATLAB本身。 My sample code is as follows: 我的示例代码如下:

function Problem1 = BisectionMethod1()
    a = input('enter function:', 's');
    f = inline(a);
    iteration_counter = 0;
    al = input('enter left bound: ');
    ar = input('enter right bound: ');
    break;
    disp(f('al'))
    disp(f('ar'))

When I set a as x+1, and set my left and right bound as 1 and 2, it displays f(al) and f(ar) correctly. 当我将a设置为x + 1并将左边界和右边界设置为1和2时,它将正确显示f(al)和f(ar)。

The problem seems to begin when I have a coefficient in front of 'x'. 当我在“ x”前面有一个系数时,问题似乎开始了。

For example, when I set a as 2x+1, and set my left and right bounds as 1 and 2, MATLAB would give me error. 例如,当我将a设置为2x + 1并将左右边界设置为1和2时,MATLAB会给我错误。

Like I said, I am new to MATLAB, is there any way to solve this? 就像我说的那样,我是MATLAB新手,有什么办法可以解决这个问题?

One point I need to make is that multiplication requires a * operator. 我需要说明的一点是,乘法需要*运算符。 By doing 2x , MATLAB would interpret this as a variable named 2x and MATLAB does not support variables where there is a number that comes first. 通过执行2x ,MATLAB会将其解释为名为2x的变量,并且MATLAB不支持在数字前面的变量。 Therefore, you need to do 2*x + 1 . 因此,您需要做2*x + 1 In addition, you need to remove your break statement. 另外,您需要删除break语句。 Your code will exit prematurely if you leave this in. 如果将其保留,则代码将过早退出。

Also, simply remove the single quotes when calling f . 另外,只需在调用f时删除单引号。 You are inputting the variable, not the actual name of the variable itself. 您输入的是变量,而不是变量本身的实际名称。 As such, you would do: 因此,您将执行以下操作:

disp(f(al));
disp(f(ar));

Using your code, this is what I get: 使用您的代码,我得到的是:

>> a = input('enter function:', 's');
enter function:2*x + 1
>> f = inline(a);
>> al = input('enter left bound:');
enter left bound:1
>> ar = input('enter right bound:');
enter right bound:2;
>> disp(f(al))
     3

>> disp(f(ar))
     5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM