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

1 view (last 30 days)
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

Answers (1)

Dyuman Joshi
Dyuman Joshi on 23 Jan 2024
Edited: Dyuman Joshi on 23 Jan 2024
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

Tags

Community Treasure Hunt

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

Start Hunting!