How can I plot cos(x)^n for n between 1 and 10 on the same plot.

4 views (last 30 days)
I'm trying to work out the error on finite difference approx for the cos hill. Ive got the current code but trying to adapt this for varying n, needed to work out the order of solution.
A= (32*pi)/7 ;
f = @(x) 0.*( x<25/64 & x>39/64) +cos(A*(x-0.5)).*( (25/64)<=x & x<=39/64);
g = @(x) 0.*( x<25/64 & x>39/64) +-A*sin(A*(x-0.5)).*( (25/64)<=x & x<=39/64);
h = 0.001;
x = 25/64:h:39\64; % this way, you define the desired step size, h, and use it to calculate the x vector
% to change the resolution, simply change the value of h
% x = linspace(-4,4,9);
n = length(x);
y=f(x);
z=g(x);
dy = zeros(n,1); % preallocate derivative vectors
ddy = zeros(n,1);
for i=2:n-1
dy(i) = (y(i+1)-y(i-1))/(2*h);
end
e= abs(g(x)-dy'); % The error function
% Now when you plot the derivatives, skip the first and the last point
figure;
plot(x,y,'r');
hold on;
plot(x(2:end-1), dy(2:end-1),'b');
grid on;
plot(x,z,'g');
plot(x,e,'k');
legend('cosx', 'dy', '-sinx','Error')

Accepted Answer

David Hill
David Hill on 8 Mar 2022
[x,n]=meshgrid(0:.01:2*pi,1:10);
f=cos(x).^n;
plot(x(1,:),f);

More Answers (0)

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!