Eulers Formula Program Help
信息
此问题已关闭。 请重新打开它进行编辑或回答。
显示 更早的评论
Hello, I need a little help with my Eulers formula program that I'm creating with Matlab. This is my following program. The issue I am having is when I input the dxdy formula, for example x+y, it is giving me the incorrect answer. However, if I put that x+y in place of the dxdy in the for loop, I get the correct answer. I just don't understand why the input x+y is different then if I manually put x+y within the for loop.
x=input('Input the initial value of "x": ');
y=input('Input the initial value of "y": ');
dxdy=input('Input the differential equation you have: ');
value=input('Input the value of the unknown function in which you want to evaluate to. (i.e if you want y(3), type in 3) \n');
step=input('Input the step size you would like: ');
for i=0:100
dy=dxdy*step;
x=x+step;
y=y+dy;
if x==value
fprintf('The estimated value of the function is %3.2f \n',y)
end
end
--------------------------------------
0 个评论
回答(1 个)
Walter Roberson
2011-11-19
When you put x+y in place of dxdy in the for loop, do you end up with
dy=x+y*step;
or do you end up with
dy=(x+y)*step;
?
Note that when you input() x+y that it evaluates the expression at the time of the input(), giving you a constant answer, whereas in either of the writings above, x and y are going to be changing because you are adding values to both of them inside the for loop.
If you want to input an expression that is to be evaluated at run time, you will need to use the 's' option of input(), and then in the loop you will need to use one of the several ways of evaluating the expression -- such as creating a function handle out of it before the loop by using str2func(), and then applying that function handle to (x,y) inside the loop. The best way to use str2func() depends on your MATLAB version; it improved somewhere around 2010b.
2 个评论
Teague
2011-11-19
Walter Roberson
2011-11-19
dxdy=input('Input the differential equation you have: ', 's');
would read in what the user typed as a character string. But then you need to find a way to evaluate that string with particular x and y values, at the appropriate time.
See http://www.mathworks.com/matlabcentral/answers/15450-convert-a-symbolic-equation-to-a-vector-equation for information about converting a string to a function handle.
When you call the function handle in the loop, make sure you provide arguments:
dy = fdydx(x,y) * step
此问题已关闭。
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!