my Plot not showing a line only the points

3 ビュー (過去 30 日間)
Mustafa Abdalla Zakiedin
Mustafa Abdalla Zakiedin 2019 年 11 月 28 日
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

採用された回答

Walter Roberson
Walter Roberson 2019 年 11 月 28 日
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 件のコメント
Mustafa Abdalla Zakiedin
Mustafa Abdalla Zakiedin 2019 年 11 月 28 日
Thank you Mr.Roberson for your response, It make sense now

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

その他の回答 (1 件)

Bhaskar R
Bhaskar R 2019 年 11 月 28 日
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
  1 件のコメント
Mustafa Abdalla Zakiedin
Mustafa Abdalla Zakiedin 2019 年 11 月 28 日
All thanks dear Bhaskar R, Its worked fine now

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

カテゴリ

Help Center および File ExchangeGeometry and Mesh についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by