need plot a graph using Euler's method for both numerical and analytical

3 次查看(过去 30 天)
% Euler's Method
% Initial conditions and setup
h = (10); % step size
x = (0):h:(60); % the range of x
y = zeros(size(x)); % allocate the result y
y(1) = (2); % the initial y value
n = numel(y); % the number of y values
for i=1:n-1
pi = 3.1416
a = 2
r = 1
f = a + (2 - 0.4*a) * x / r^2 * pi
y(i+1) = y(i) + h * f;
end
plot (x,y,'b')
grid on
  4 个评论
Mpho Mokgotlo
Mpho Mokgotlo 2022-10-30
Thank you for the help. tht ting is when I try to plot the graph it gives out error message like : unable to perform assignment because the left and right sides have a different number of element, so I was asking what should I do or change and how
Jan
Jan 2022-10-30
@Mpho Mokgotlo: If you mention an error, post a copy of the complete error message. Seeing some parts of the message only is less useful, e.g. the readers do not know, in which line the error occurs.

请先登录,再进行评论。

回答(2 个)

Alan Stevens
Alan Stevens 2022-10-30
编辑:Jan 2022-10-30
f = a + (2 - 0.4*a) * x(i) / r^2 * pi; % x(i) not just x.
% Also take note of the other comments above.

Jan
Jan 2022-10-30
h = 10; % step size
x = 0:h:60; % the range of x
y = zeros(size(x)); % allocate the result y
y(1) = 2; % the initial y value
n = numel(y); % the number of y values
a = 2;
r = 1;
for i = 1:n-1
f = a + (2 - 0.4 * a) * x(i) / r^2 * pi;
% ^^^
y(i+1) = y(i) + h * f; % I guess this line fails
end
plot (x,y,'b')
grid on
A cleaned version of your code. Alan Stevens' hint is included (please accept his answer).
You can solve such problems using the debugger. Type in the command window:
dbstop if error
and run the code again. Matlab stops at the problem and you can check the values of the used variables.
size(y(i+1)) % A scalar, of course
size(y(i) + h * f) % Not a scalar
size(f) % Same size as x!
You do not want x in the line to get the value of f, but only the element x(i).
Do you really mean: ... / r^2 * pi or .../ (r^2 * pi) ?

类别

Help CenterFile Exchange 中查找有关 Graphics Performance 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by