필터 지우기
필터 지우기

Strange Problem when i write same code in function

조회 수: 2 (최근 30일)
moonman
moonman 2011년 11월 5일
This is my original code for Bisection Methods of Numerical Analysis
% A program in matlab
% bisection method to find the roots of x^3+x^3+5=0
xleft = -2.5 ; xright = -1.5 ; n = 20
format longe
% Input: xleft,xright = left and right brackets of the root
% n = (optional) number of iterations; default: n =15
% Output: x = estimate of the root
if nargin<3, n=15; end % Default number of iterations
a = xleft; b =xright; % Copy orig bracket to local variables
fa = a^3 + a^2 + 5; % Initial values
fb = b^3 + b^2 +5; % Initial values
fprintf(' k a xmid b f(xmid)\n');
for k=1:n
xm = a + 0.5*(b-a); % Minimize roundoff in the midpoint
fm = xm^3 + xm^2 +5; % f(x) at midpoint
fprintf('%3d %12.8f %12.8f %12.8f %12.3e\n',k,a,xm,b,fm);
if sign(fm) == sign(fa)
a = xm; fa = fm;
else
b = xm; fb = fm;
end
end
**************************************** Now i am writing the same function by manually giving input
my main file is this one
input('Type value of a \n');
input('Type value of b\n');
bisec(a,b)
and my function file is this one
function bisec(a,b)
format longe
n=20;
% Output: x = estimate of the root
*fa = a^3 + a^2 + 5; % Initial values
fb = b^3 + b^2 +5; % Initial values* _ITALIC TEXT_
fprintf(' k a xmid b f(xmid)\n');
for k=1:n
xm = a + 0.5*(b-a); % Minimize roundoff in the midpoint
fm = xm^3 + xm^2 +5; % f(x) at midpoint
fprintf('%3d %12.8f %12.8f %12.8f %12.3e\n',k,a,xm,b,fm);
if sign(fm) == sign(fa)
a = xm; fa = fm;
else
b = xm; fb = fm;
end
end
end
But my results are comming different plz guide me

채택된 답변

Fangjun Jiang
Fangjun Jiang 2011년 11월 5일
try
a=input('Type value of a \n');
b=input('Type value of b\n');

추가 답변 (2개)

moonman
moonman 2011년 11월 5일
Thanks a lot Fangjun u saved my time and problem is resolved Can u explain what is wrong in my input commands
  댓글 수: 1
Walter Roberson
Walter Roberson 2011년 11월 5일
You are not assigning the results of the input() to any variable.

댓글을 달려면 로그인하십시오.


moonman
moonman 2011년 11월 5일
I also need one more help. I have to follow this instruction
write a separate function file called f.m that stores the definition of the function: for part (i) this will be function y=f(x) y=x.^3+x.^2+5; You can then use f(x) in your bisection M-file
Right now i am writing this function manually and it is shown in italic

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by