How to include a negative number in initial conditions for Eulers method code?

8 ビュー (過去 30 日間)
Alex
Alex 2023 年 12 月 13 日
編集済み: Torsten 2023 年 12 月 13 日
clear
close all
h=0.1; % step size
x=-1:h:2; % x interval define here
y=zeros(size(x));
y(-1)=8; % intial condition
n=numel(y);
for i = 1:n-1
dydx=((2.*x.*y.^2+4)/(2.*(3-y.*x.^2)))
y(i+1) = y(i)+dydx*h;
end
plot(x,y,'ro');
hold on
f1=exp(x);
plot(x,f1,'b');
grid on;
I'm writing some code for Eulers method and my initial condition is y(-1)=8. However when I run this it comes up with the error message saying array indicies must be positive integers or logical values. Any advice on how i can include my intial condition without these error messages?
  3 件のコメント
Alex
Alex 2023 年 12 月 13 日
I don't fully understand what you're saying
Torsten
Torsten 2023 年 12 月 13 日
編集済み: Torsten 2023 年 12 月 13 日
y(i) means the value of the function y at x(i).
It does not mean the value of the function y at x = i.
Since
x=-1:h:2; % x interval define here
you thought you could use y(-1) for y (x=-1).
But you must use y(1) for y @ x(1) = -1.

サインインしてコメントする。

回答 (1 件)

Les Beckham
Les Beckham 2023 年 12 月 13 日
It is always better to post example code as text rather than a screenshot. Nevertheless...
Since the first element of x is -1 and you want to specify the value of y when x is -1, just define the first element of y, y(1), with your initial condition
y(1) = 8;
  2 件のコメント
Alex
Alex 2023 年 12 月 13 日
I've tried this but it still doesn't produce the answer im after. Is there anything else incorrect with the code?
Torsten
Torsten 2023 年 12 月 13 日
dydx=((2.*x(i).*y(i).^2+4)/(2.*(3-y(i).*x(i).^2)))
instead of
dydx=((2.*x.*y.^2+4)/(2.*(3-y.*x.^2)))
And your denominator becomes 0 in the course of the integration - thus your solution has a singularity.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by