I am trying to implement AHP(Analytic Hierarchy Process) algorithm for computing criterion's weights(using eigen vetors). For example, I want to buy a smart phone. My criteria are: color, memory, delivery. For computing weights I have to make pair wise comparison among criteria. I will compare color with memory, color with delivery, and memory with delivery.
For comparing 2 criteria, we use a scale from 9 to 1/9.
For example I compare color with memory: if in my opinion color is more important than memory 4 times, I will use 4 ,if color has the same importance like memory, I will use 1, if color is less important than memory 4 times, I use 1/4=0.25.
For computing weights, I have to build a matrix:
color memory delivery
color 1 value1 value2
memory 1/value1 1 value3
delivery 1/value2 1/value3 1
In my case the matrix is 3x3 because I have only 3 criteria. The program is working for 3 criteria, but not for 4, 5 or more. After the matrix is build, I can compute eigen vectors that will give me the weights.Any suggestion would be appreciated. Thank you in advance!
Here is the code for Criteria class:
public class Criteria
{
public static void main(String[] args)
{
AHP ahp=new AHP();
int n;
int NUMBER_COMPARISON;
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the number of criteria");
System.out.println("n=");
n=keyboard.nextInt();
NUMBER_COMPARISON=(n*n-n)/2;
double [][] a=new double[n][n];
String [] criteria=new String[n];
double [] p=new double[NUMBER_COMPARISON];//used to hold the values of comparisons
System.out.println("Enter the criteria:");
for(int i=0; i<n;i++)
{
System.out.print("Criterion "+(i+1)+":");
criteria[i]=keyboard.next();
}
System.out.println("Enter the comparison");
int m=0;
for(int i=0; i<n;i++)
{
for(int j=i+1; j<n;j++)
{
System.out.println("Compare "+criteria[i]+" with "+criteria[j]+":");
p[m]=keyboard.nextDouble();
m++;
}
}
a=ahp.initialize_matrix(p);
ahp.show_matrix(a);
}
}
Here is the code for AHP class:
public class AHP
{
public static double[][] initialize_matrix(double[] p)
{
//initialize the matrix a
double a[][]=new double[p.length][p.length];
int k=0;
for(int i=0; i<p.length; i++)
{
for(int j=0; j<p.length;j++)
{
if(i==j)
a[i][j]=1;
else if(i<j)
{
a[i][j]=p[k];
k++;
}
else if(i>j)
a[i][j]=1/a[j][i];
}
}
return a;
}
public static void show_matrix(double[][] b )
{
//display the elements of the matrix a
System.out.println("\nThe matrix a is:");
for(int i=0; i<b.length;i++)
{
for(int j=0; j<b[i].length; j++)
System.out.print(b[i][j]+" ");
System.out.println();
}
}
}