Write a Matlab program called iterate.m which plots the curves y=x and y=cos(x)
ID: 1862007 • Letter: W
Question
Write a Matlab program called iterate.m which plots the curves y=x and y=cos(x) on the same plot for x values between 0 and 1.5, then uses iteration to find the solution with x>0 to the equation
x = cos(x)
For the iteration loop, you will need to choose an appropriate initial value of x and an appropriate number of iteration steps.
For this problem, upload the file iterate.m
Ihave plotted them, but when it comes to the iteration i do not get the right answer. This is my program,
x-values
x= 0:.01:1.5;
% equations of curves
y1 = x;
y2 = cos(x);
%plotting for both curves
plot(x,y1,'r');
hold on
plot(x,y2,'g');
for x=(0.1:0.001:2);
x=cos(x);
end
disp(x)
Explanation / Answer
clc
clear
x= 0:.01:1.5;
% equations of curves
y1 = x;
y2 = cos(x);
%plotting for both curves
plot(x,y1,'r');
hold on
plot(x,y2,'g');
xlabel('x')
ylabel('y')
legend('y = x','y = cos(x)')
x0 = 0.5; %initial value of x
err = 1; %error term. Value of err = 1 is assigned just to initialize the loop,
%later the error will be calculated after each iteration
while err>10^(-5) %loop will work untill the error is less than 0.00001
x1 = x0;
x0 = cos(x0);
err = abs(x1-x0);
end
a = sprintf('solution of x=cos(x) is at x = %1.5f ',x0);
disp(a)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.