2014-04-27 2 views
1

안녕하세요, 구간 [a, b]에서 함수의 루트를 찾으려면 이분법을 구현해야합니다. 알고리즘은 루트 "c"를 반환해야합니다. 2. 함수 값 "yc"3. 반복 횟수 "itcount". 여기Bisection Matlab 구현 문제

내가 지금까지 무엇을 가지고 :

function [ r, c, yc, itcount] = bisection(f, a, b, N, eps) 
% Check that that neither end-point is a root 
% and if f(a) and f(b) have the same sign, throw an exception. 

if (f(a) == 0) 
r = a; 
return; 
elseif (f(b) == 0) 
r = b; 
return; 
elseif (f(a) * f(b) > 0) 
    error('f(a) and f(b) do not have opposite signs'); 
end 

% We will iterate N times and if a root was not 
% found after N iterations, an exception will be thrown. 

for k = 1:N 
    % Find the mid-point 
    c = (a + b)/2; 
    yc = feval(f,c); 
    itcount = abs(b-a)/2; 
    % Check if we found a root or whether or not 
    % we should continue with: 
    %   [a, c] if f(a) and f(c) have opposite signs, or 
    %   [c, b] if f(c) and f(b) have opposite signs. 

    if (f(c) == 0) 
     r = c; 
     return; 
    elseif (f(c)*f(a) < 0) 
     b = c; 
    else 
     a = c; 
    end 

    % If |b - a| < eps_step, check whether or not 
    %  |f(a)| < |f(b)| and |f(a)| < eps_abs and return 'a', or 
    %  |f(b)| < eps_abs and return 'b'. 

    if (b - a < eps) 
     if (abs(f(a)) < abs(f(b)) && abs(f(a)) < eps) 
      r = a; 
      return; 
     elseif (abs(f(b)) < eps) 
      r = b; 
      return; 
     end 
    end 
end 

error('the method did not converge'); 
end 

나는 이미 내가의 뿌리를 찾으려는 기능에 대해하는 .m 파일을 만들었습니다. 그리고 알고리즘은 작동하지만 루트 만 반환하지만 함수 값과 반복 횟수는 반환하지 않습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

답변

0

귀하의 알고리즘이 올바른 것으로 보입니다. 출력을 벡터로 가져와야합니다.

[r, c, yc, itcount] = bisection(@f,.......) 

과 같이 호출하면 단지 당신에게

an = bisection(@f,.......) 

이 스레드 -을 볼 수있는 첫 번째 요소를 얻을 것이다> MATLAB - multiple return values from a function?