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

조회 수: 4 (최근 30일)
Zoe Westcott
Zoe Westcott 2022년 3월 8일
답변: David Hill 2022년 3월 8일
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')

채택된 답변

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by