Can anyone help me what's wrong with this coding?
1 view (last 30 days)
Show older comments
function graph1
clear
clc
ask1 =input('Enter f(x) =','s');
f = inline(ask1);
c=0;
a = input('Enter the value of a : ');
b = input('Enter the value of b : ');
tol = input('Enter the tolerance value : ');
f(x) =@(x) (x.^2 + 2*x + 2)*(x-sqrt(3));
maxiteration = input('Enter the maximum number of iteration : ');
iteration = 0;
%ainitial = a; % Stores initial boundaries for plotting.
%binitial = b;
fprintf('a = %2.6f\nb = %2.6f\n\nat iteration%2i ', a, b, iteration)
fprintf('\n\n a b iteration no.')
while(f(a)*f(b)>0)
disp('try enter new values : ');
a = input('Enter the value of a : ');
b = input('Enter the value of b : ');
end
while (abs(c)) < tol % Loop ends when condition is violated.
while iteration<maxiteration
c = (a + b)/2; % Calculates the midpoint of a and b.
if f(c) < 0 % <<<
a = c; % <<< Reassigns a and b values
elseif f(c) > 0 % <<< depending on above result.
b = c; % <<<
end
%plot(xplot,f(xplot),'r', ainitial, f(ainitial),'b*', binitial, f(binitial),'g*',a,f(a),'bo',b,f(b),'go','markersize',10) % Plots function and
title('Graph of f(x)') % displays root at
xlabel('x') % each iteration.
ylabel('f(x)')
Labels = legend('Initial a','Initial b','a','b');
set(Labels,'location','north')
iteration = iteration + 1; % Updates iteration no.
if abs(a) < 10
fprintf('\n%2.6f %11.6f%10i', a, b, iteration) % Correctly alligns
else % command outputs.
fprintf('\n%2.6f%11.6f%10i', a, b, iteration)
end
pause(0.5) % Shows values at each iteration. .
end
end
fprintf('\n\nRoot is %2.6f after %2i iterations. \n\n', a, iteration) % Displays root
end
1 Comment
Image Analyst
on 29 Jun 2020
Edited: Image Analyst
on 29 Jun 2020
Please edit your post. Highlight your code, then click the Code icon so that people can copy it to the clipboard with a single click.
One problem is that you call clear as the first line. There is no need to do that since each function has its own workspace, plus if you ever do pass in anything via the input argument list, that will delete the variable so that you would not be able to use it inside the function.
Now, what are you typing in when it prompts you?
Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices 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!