Advertisement
elisim

ass4_q3

Jul 14th, 2017
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Julia 1.03 KB | None | 0 0
  1. # Eli Simhayev - 2017
  2. # Question 3
  3.  
  4. n = 5;
  5. maxIter = 50;
  6.  
  7. # ===== Task C =====
  8.  
  9. # calculate the coefficient of xᵢ - g.
  10. function calc_g(i,H,g,x)
  11.     sum = 0;
  12.     for j=1:n
  13.         if j != i
  14.             sum += H[i,j]*x[j];
  15.         end
  16.     end
  17.  
  18.     return sum - g[i];
  19. end
  20.  
  21. function projected_CD(H,g,a,b,x_CD)
  22.     for i=1:n
  23.         g_coe = -calc_g(i,H,g,x_CD); # g coefficient
  24.         h_coe = H[i,i];              # h coefficient
  25.         g_div_h = g_coe/h_coe;
  26.  
  27.         if g_div_h < a[i]
  28.             x_CD[i] = a[i];
  29.         elseif g_div_h > b[i]
  30.             x_CD[i] = b[i];
  31.         else
  32.             x_CD[i] = g_div_h;
  33.         end
  34.     end
  35.  
  36.     return x_CD;
  37. end
  38.  
  39.  
  40. # ===== Task D =====
  41. H = [5 -1 -1 -1 -1;
  42.      -1 5 -1 -1 -1;
  43.      -1 -1 5 -1 -1;
  44.      -1 -1 -1 5 -1;
  45.      -1 -1 -1 -1 5];
  46.  
  47. g = [18; 6; -12; -6; 18];
  48. a = zeros(n); b = 5*ones(n);
  49.  
  50. x_CD = zeros(n); # guess
  51. for i=1:maxIter
  52.     x_CD = projected_CD(H,g,a,b,x_CD);
  53. end
  54.  
  55. println("x_CD = ", x_CD); # x_CD = [5.0,3.66667,0.666667,1.66667,5.0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement