Matlab Script Accuracy of Results

3 次查看(过去 30 天)
I'm trying to write a Matlab script that shows the order of accuracy of the forward and central differencing methods for the first derivative of f = exp (x) at x = 0. The graph attached is the result I'm looking for.
Here is what I have so far in forward differencing method but I'm kinda stuck. Can you show me where I made my mistakes.
clear all
close all
delx = 1;
x = 0;
y = exp(x);
fig = figure();
set(fig,'color','white')
plot(x,y,'LineWidth',2)
xlabel('x')
ylabel('y')
grid on
yderiv = exp(x);
fig = figure();
set(fig,'color','white')
plot(x,yderiv,'LineWidth',2)
xlabel('x')
ylabel('y')
grid on
%%%Forward Differencing
yderivest = (y(2:end) - y(1:end-1))./delx;
hold on
plot(x(2:end)-delx/2,yderivest,'r-','LineWidth',2)

采纳的回答

John D'Errico
John D'Errico 2017-10-19
You made a LOT of mistakes.
delx = 1;
x = 0;
y = exp(x);
So you set x to zero. Then you evaluated exp(x).
That does NOT create a function of x. It simply evaluates exp(x), thus, here exp(0).
And I'm not sure what you think you are doing here:
yderivest = (y(2:end) - y(1:end-1))./delx;
y is a scalar variable. It is not a vector as you built it.
I'll give you a couple of suggestions to get you started.
Generate a vector of h values. Something like this:
h = 2.^(-20:1:0);
And you might create a function.
testfun = @(x) exp(x);
Now your code will work for other functions, doing not much more than changing testfun.
So what would this do?
x0 = 0;
fdiff = (testfun(x0 + h) - testfun(x0))./h
How would you change that for a central difference?
What is the error in the derivative approximation? Well, you know that the correct derivative is just:
truederiv = exp(x0);
fdifferr = abs(truederiv - fdiff);
Now you can plot the result as a function of h. Plot will work, but perhaps loglog will be a better choice of plotting tool. Think about why that might be true. What does the slope of such a resulting error plot mean when you plot it using loglog axes?
  1 个评论
jcn2912
jcn2912 2017-10-19
How do I plot the result as a function of h? I'm not getting the answer I'm looking for.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by