The conjugate gradient method is a mathematical technique that can be useful for the optimization of both linear and non-linear systems. This technique can be used as an iterative algorithm, and also as a direct method, and it will produce a numerical solution. Generally this method is used for very large systems where it is not practical to solve with a direct method.
We initially start with an initial guess of the solution and then we calculate the gradient to find a first direction to move. During the next iterations, the directions have to be conjugate to the previous ones, thereby assuring the conditions of the previous section.
Let u, v be vectors in R^n and let A be a positive definite n×n matrix. u and v are said to be mutually A-conjugate if and only if u’Av=0 where u’ represents u transpose.
As in gradient descent, we start with a guess x0 for x and calculate the gradient at that point, which will be Ax0−b. We take the first conjugate vector p1 in the opposite direction and make the step x1=x0+α1p1. Now on we have to guarantee that the next steps are in conjugate directions to the previous. Hence, for every residual rk=b−Axk. we need to build the conjugate by making it orthogonal to the previous ones (this is done by removing any projection of the current residual in the previous conjugate vectors).
βik is the projector operator of rk on pi. After that, we make the step in the direction of the new conjugate vector x(k+1).
Step size is defined as αk=(p_k’)(b)/(p_k’)(A)(p_k).
Pseudo Code:

Java Code:
Importing Libraries and Function create a range of values with defined interval.

Function to print the matrix and Function to multiply a matrix with a scalar value.

Function to create random matrix.

Function for Conjugate Gradient.

Class – three_mat for returning three matrices namely x_mat (solution), p_mat (direction), and r_mat (residual).

To check whether the residuals are perpendicular to directions. It can also be used to check between residuals and also between directions

Main Function:

Output:

Code and Libraries at https://github.com/Prasanth-s-n/Java_Code
This is the Second Blog in Gradient Based Optimization Algorithm Series. Check out my previous blogs and other blogs.
Hope this is helpful.
Thank you, Have a great day.
PLEASE FEEL FREE TO SEND FEEDBACK OR COMMENT TO IMPROVE US




