what's the difference

1 次查看(过去 30 天)
I want to piecewise plot a interlolation function. When I input the nodes like this
X = -1:0.1:1;
N = length(X);
the graph is continuous like this
However When I input the nodes like this :
X = zeros(1,21);
N = 21;
for i = 1: 21
X(i) = -1 + 2*(i-1)/(N-1);
there is an obvious gap in the graph like this :
I suppose these two codes are exactly the same, why the graphs are different??
the codes are as follows:
tic
clc
clear
f = @(x)1./(1+25.*x.^2);
syms x
f_dri = diff(f(x));
%X = -1:0.1:1;
%N = length(X);
X = zeros(1,21);
N = 21;
F = zeros(1, N);
F_dri = zeros(1, N);
for i = 1 : N
X(i) = -1 + 2*(i-1)/(N-1);
F(i) = f(X(i));
F_dri(i) = subs(f_dri, x, X(i));
end
for j = 1 : N-1
M = zeros(4,4);
M(1,1) = F(j);
M(2,1) = F(j);
M(3,1) = F(j+1);
M(4,1) = F(j+1);
M(2,2) = F_dri(j);
M(3,2) = (F(j+1)-F(j))/(X(j+1)-X(j));
M(4,2) = F_dri(j+1);
M(3,3) = (M(3,2)-M(2,2))/(X(j+1)-X(j));
M(4,3) = (M(4,2)-M(3,2))/(X(j+1)-X(j));
M(4,4) = (M(4,3)-M(3,3))/(X(j+1)-X(j));
f_inp = M(1,1)+(x-X(j))*M(2,2)+(x-X(j))^2*M(3,3)+(x-X(j+1))*(x-X(j))^2*M(4,4);
a = X(j):0.01:X(j+1);
b = subs(f_inp, x, a);
G = plot(a, b, 'r', 'LineWidth', 2);
hold on
end
saveas(gcf, 'pic_2', 'jpg');
% r = -1:0.01:1;
% f_ori = f(r);
% G(5) = plot(r, f_ori, 'k', 'LineWidth', 2);
legend(G,'N=21');
toc

采纳的回答

Walter Roberson
Walter Roberson 2019-5-6
X(13) is eps/4 less than 0.2 . When you use X(j):0.01:X(j+1) that is just enough that the previous plot ends at 0.19 instead of 0.20
Always remember that when you calculate your endpoints using floating point numbers that they will usually not be **exactly* nice multiples of 1/10 or 1/100 .
  2 个评论
zilai si
zilai si 2019-5-7
thanks, i undersatand. But how to solve such problems?
Walter Roberson
Walter Roberson 2019-5-7
You have a fundamental mismatch of expecting that breaking up the range 0 to 1 into (N-1) subdivisions (N total points including both endpoints) will give you ranges that are nicely divisible into increments of 0.01
Instead of using X(j):0.01:X(j+1) consider using a = linspace(X(j), X(j+1), 11)

请先登录,再进行评论。

更多回答(0 个)

类别

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

产品

Community Treasure Hunt

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

Start Hunting!

Translated by