my Plot not showing a line only the points

3 Ansichten (letzte 30 Tage)
Mustafa Abdalla Zakiedin
Mustafa Abdalla Zakiedin am 28 Nov. 2019
I need to show the plot with continous line but it keep plotting only the points, I don't understand the reason .
% Numerical Method of Solving ODE \ Euler Method%
'Example (1)''dy/dx=-y'
dy = @(x,y)-y;
f = @(x)exp(-x);
x0 = 0;
xn = 1;
y = 1;
h = 0.1;
fprintf (' x \t\t y (Euler)\t y(Exact) \n') % data table header
for x = x0 : h : xn-h
y = y + dy(x,y)*h;
x = x + h;
hold on
plot(x,y,'or');
xlabel('X');
ylabel('Y-by Euler method');
hold on
y2 = f(x);
plot(x,y2,'ob')
hold off
fprintf ('%f \t %f\t %f\n',x,y,f(x));
end

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 28 Nov. 2019
At any one time your x and y are scalar. plot() only produces lines when there are at least two adjacent finite points in a single plot call.
You should store all the x and y values and do the plot all at once afterwards.
  1 Kommentar
Mustafa Abdalla Zakiedin
Mustafa Abdalla Zakiedin am 28 Nov. 2019
Thank you Mr.Roberson for your response, It make sense now

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Bhaskar R
Bhaskar R am 28 Nov. 2019
If you need plot as line in anyway take additional variables to plot it
% Numerical Method of Solving ODE \ Euler Method%
% 'Example (1)''dy/dx=-y'
dy = @(x,y)-y;
f = @(x)exp(-x);
x0 = 0;
xn = 1;
y = 1;
h = 0.1;
fprintf (' x \t\t y (Euler)\t y(Exact) \n') % data table header
% initialize dummy of the x, y, y2 as dummy so that you can plot outside
dummy_x = zeros(1, length(x0 : h : xn-h));
dummy_y = zeros(1, length(x0 : h : xn-h));
dummy_y2 = zeros(1, length(x0 : h : xn-h));
k = 1; % counter variable
for x = x0 : h : xn-h
y = y + dy(x,y)*h;
x = x + h;
dummy_y(k) = y;
dummy_x(k) = x;
y2 = f(x);
dummy_y2(k) = y2;
fprintf ('%f \t %f\t %f\n',x,y,f(x));
k = k+1;
end
figure, hold on
plot(dummy_x,dummy_y,'-o');
xlabel('X');
ylabel('Y-by Euler method');
hold on
plot(dummy_x, dummy_y2,'-o')
hold off

Community Treasure Hunt

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

Start Hunting!

Translated by