Trying to plot the output of a function where h is a range over 10^-1 to 10^-18

2 次查看(过去 30 天)
Hello I am trying to answer this question :
Using a suitable graph, show the output of your function with x fixed at 0.25, and with values of h ranging from 10-1 to 10-18.
However it seems that I am not setting the h range the right way nor am i plotting it the right way.
function AD = absolutediff(x)
for h = 10^-1:10^-18
f = @(x) cos(x);
f1 = @(x) -sin(x);
AD = f1(x) - ((f(x+h)-f(x))./h);
plot(x,AD)
end

回答(1 个)

Dyuman Joshi
Dyuman Joshi 2024-1-23
编辑:Dyuman Joshi 2024-1-23
We can take advantage of the vectorization here -
AD = absolutediff(2.5)
AD = 1×35
-0.5985 -0.5985 -0.5985 -0.5985 -0.5985 0.4548 -0.0434 -0.0016 0.0122 -0.0016 -0.0001 0.0001 0.0000 0.0000 0.0000 -0.0000 0.0000 0.0000 0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0001
function AD = absolutediff(x0)
%Function definitions
f = @(x) cos(x);
f1 = @(x) -sin(x);
fun = @(x, h) f1(x) - ((f(x+h)-f(x))./h);
%h values for example
h = 10.^(-18:0.5:-1);
%Calculate the value of the function for a given x and set of h-values.
AD = fun(x0, h);
%plot h vs AD as a red line with asterisks as marker
plot(h, AD, 'r-*')
%Adjust the x-ticks
xticks(10.^(-18:-1))
%Change the scale of x-axis to log for a better appearance of the graph
set(gca, 'XScale', 'log')
end

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by