What is wrong with my code for the bisection method!!?
    3 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Britney
 el 8 de Oct. de 2014
  
    
    
    
    
    Comentada: Britney
 el 9 de Oct. de 2014
            So I have this code I need too use on my a function.
I have made m. function file with the function I want to calculate.
f=@(x)(x-2.5).*exp(-0.5*(x-2).^2)+0.2;
x=my_bisect(f,[-1,0],1e-5);
m =(a+b)/2; 
disp(m);
And in another file I have this code:
function m=my_bisect(funktion, int , tol )
a = int (-1);
b = int (0);
fa =funktion(a) ;
fb =funktion(b) ; 
disp(fa)
disp(fb)
msg=sprintf('??? error.');
while b-a > tol 
      m = (a+b)/2; 
      fm = funktion(m); 
      if fm==0
      disp(msg)
      return 
      end
      if fa * fm < 0 
      b = m; 
      fb = fm; 
      else 
      a = m; 
      fa = fm; 
      end
end
When I try running function file to find m Matlab returns: Attempted to access int(-1); index must be a positive integer or logical.
What is wrong?
0 comentarios
Respuesta aceptada
  Geoff Hayes
      
      
 el 8 de Oct. de 2014
        Britney - the error message is telling you that you are trying to access an array named int with an index that is not positive or a logical (true/1). In your case, the first two lines of your code are
 a = int (-1);
 b = int (0);
and you are using -1 and 0 to index the array. As neither are positive, the error message makes sense. If a and b are the endpoints for your interval, then you can initialize them as
 a = int(1);
 b = int(2);
Though you may want to rename this input variable as interval as int could be mistaken for integer.
Note that since you are using double precision, the line
 if fm==0
is not guaranteed to ever evaluate to true. This is fine for integers, but for variables of type double, you would typically do something like
 if abs(fm)<tol
where tol is some small number (could be eps).
Más respuestas (0)
Ver también
Categorías
				Más información sobre Logical en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

