java AHP算法仅适用于3个标准
我试图实现AHP(层次分析法)算法来计算标准的权重(使用特征向量)。例如,我想买一部智能手机。我的标准是:颜色、记忆力、交货期。为了计算权重,我必须对标准进行成对比较。我会比较颜色与记忆,颜色与传递,记忆与传递。
为了比较两个标准,我们使用了从9到1/9的量表。
例如,我将颜色与记忆进行比较:如果我认为颜色比记忆重要4倍,我将使用4,如果颜色与记忆同等重要,我将使用1,如果颜色比记忆不重要4倍,我使用1/4=0.25
为了计算权重,我必须建立一个矩阵:
color memory delivery
color 1 value1 value2
memory 1/value1 1 value3
delivery 1/value2 1/value3 1
在我的例子中,矩阵是3x3,因为我只有3个标准。该计划适用于3个标准,但不适用于4、5或更多标准。在矩阵建立之后,我可以计算特征向量,从而得到权重。如有任何建议,将不胜感激。提前谢谢
以下是标准类的代码:
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);
}
}
以下是AHP类的代码:
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();
}
}
}
# 1 楼答案
从分析的角度来看,初始化_矩阵方法中的变量j和i总是在数组边界内。 但是,变量k可以增加p.length^2倍。当您还使用此变量访问数组p时,它必须为<;p、 长度
我认为你想在k位置增加价值,但每一行都是在线的。我建议在完成内部for循环后将k设置为零
编辑:正如预测的那样
n=4时的输出:
输入条件的数量 n= 4. 输入条件: 标准1:a 标准2:b 标准3:c 标准4:d 输入比较 比较a和b: 0.3 比较a和c: 0.1 比较a和d: 0.6 比较b和c: 0.5 比较b和d: 0.8 比较c和d: 0.2
矩阵a是: 1.0.30.1 0.6 0.5 0.8
3.3335 1.0 0.30.1 0.6 0.5
10.0 3.3335 1.0 0.3 0.1 0.6
1.66666667 10.0 3.3335 1.0 0.3 0.1
3330.660.661 1.25 2.0 1.66666667 10.0 3.3333335 1.0
方法
如果您能将问题标记为已回答,我将不胜感激