简体   繁体   English

无法识别的 function 或变量“x”。 在 matlab

[英]Unrecognized function or variable 'x'. in matlab

trying to write Matlab code to implement Euler's Method to solve the differential equation y'=2+2x-x2 subject to initial condition y(0)=1.尝试编写 Matlab 代码来实现欧拉方法来求解微分方程 y'=2+2x-x2 受限于初始条件 y(0)=1。 Please use step size 0.1 and estimate the value at x=1 and x=2.请使用步长 0.1 并估计 x=1 和 x=2 处的值。

when i run the code i get Unrecognized function or variable 'x'当我运行代码时,我得到无法识别的 function 或变量“x”

dy =(2+2*x-2^2);

  x0 = 1;


  xn = 2;


  y = 1;

  h = 0.1;

  fprintf ('x \t\t y (Euler)\t y (analytical)\n') %data table header 

  fprintf ('%f \t %f\t %f\n' ,x0,y,(x0));


  for x = x0 : h : xn-hypot

   y= y + 2+2*x-2^2 * h;


  x = x + h;


  fprintf ('%f \t %f\t %f\n',x,y,(x));

 end

The problem is on the first line of the code:问题出在代码的第一行:

dy =(2+2*x-2^2);

as this is the first statement of the code, the variable x has not been declared and Matlab returns the error you provided.由于这是代码的第一条语句,变量x尚未声明,并且 Matlab 返回您提供的错误。

I would like also to add two comments:我还想补充两条评论:

  1. Because in the for loop you already typed in the derivative, y= y + 2+2*x-2^2 * h;因为在 for 循环中您已经输入了导数, y= y + 2+2*x-2^2 * h; , you do not need to state the derivative in the beginning of the code. ,你不需要 state 在代码开头的导数。 Either comment or delete the first line.评论或删除第一行。

  2. However, a better approach to make the Euler Method a little more general, is to use function handles .但是,使欧拉方法更通用的更好方法是使用function 句柄 Then you can type in the first line of the code然后你可以输入第一行代码

    dy = @(x) (2+2*x-2^2);

and in the for loop use this function:并在 for 循环中使用此 function:

for x = x0 : h : xn-hypot
   y = y + dy(x) * h;
   x = x + h;
end

This way, you do not need to change your for loop with the Euler method, and it actually works for any first order differential equation (just change the dy function).这样,您无需使用 Euler 方法更改 for 循环,它实际上适用于任何一阶微分方程(只需更改dy函数)。

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

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