Advertisement
lukicdarkoo

Kubna metoda - Minimum kod jednodimenzionih promjenjivih

Nov 21st, 2015
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.22 KB | None | 0 0
  1. function [xout yout] = kubna(f, fd, sstart, eend, e)
  2.     x = [];
  3.     x(1) = sstart;
  4.     x(2) = eend;
  5.    
  6.     while true
  7.         % a + bx + cx^2 + dx^3 = f(x)
  8.         % b + 2cx + 3dx^2 = f'(x)
  9.         amat = [
  10.             1 x(1) x(1)^2 x(1)^3;
  11.             1 x(2) x(2)^2 x(2)^3;
  12.             0 1 2*x(1) 3*x(1)^2;
  13.             0 1 2*x(2) 3*x(2)^2;
  14.         ];
  15.         bmat = [f(x(1)); f(x(2)); fd(x(1)); fd(x(2))];
  16.         abcd = linsolve(amat, bmat);
  17.         a = abcd(1);
  18.         b = abcd(2);
  19.         c = abcd(3);
  20.         d = abcd(4);
  21.  
  22.         % Trazimo x12 za y'(x) = 0
  23.         x12 = [];
  24.         x12(1) = (-2*c + sqrt(4 * c^2 - 4*b*3*d)) / (2*3*d);
  25.         x12(2) = (-2*c - sqrt(4 * c^2 - 4*b*3*d)) / (2*3*d);
  26.  
  27.         % Trazimo Xopt
  28.         y = @(x)(a + b*x(1) + c*x^2 + d*x^3);
  29.         xopt = x12(2);
  30.         if (y(x12(1)) < y(x12(2)))
  31.             xopt = x12(1);
  32.         end
  33.  
  34.         % xopt postavljamo kao novu granicu
  35.         if fd(xopt) < 0
  36.             x(1) = xopt;
  37.         else
  38.             x(2) = xopt;
  39.         end
  40.  
  41.         % Ponvaljamo dok se greska ne bude manje od e
  42.         if abs(y(xopt) - f(xopt)) < e
  43.             break;
  44.         end
  45.     end
  46.    
  47.     xout = xopt;
  48.     yout = f(xopt);
  49. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement