我尝试将2个矩阵相乘。 我尝试使用R软件:检查此主题:Multiplying two matrices in R
现在我尝试用Java做同样的事情。
我使用Jama库作为矩阵。
我的力量功能
public Matrix power(Matrix M, double p) {
EigenvalueDecomposition evd = M.eig();
Matrix D = evd.getD();
for (int i = 0; i < D.getColumnDimension(); i++) {
D.set(i, i, Math.pow(D.get(i, i), p));
}
Matrix V = evd.getV();
return V.times(D.times(V.transpose()));
}
double[][] matDouble1 = {{0.25, 0.25, 0.25, 0.25}};
double[][] matDouble2 = {{0, 0, 1, 0},
{0.333, 0, 0.333, 0.333},
{1, 0, 0, 0},
{0, 1, 0, 0}};
Matrix mat1 = new Matrix(matDouble1);
Matrix mat2 = new Matrix(matDouble2);
mat2 = power(mat2, 10000);
mat1 = mat1.times(mat2.transpose());
什么时候显示mat1我得到:
0.25018740608813655 0.2498123125257854 0.2501874060881363 0.24981231252578548
而不是
0.5 0 0.5 0
与R i做
mpower = function(M,p) {
A = as.matrix(M)
if (dim(A)[1] != dim(A)[2]) stop("not a square matrix")
# M^{-1} = the matrix inverse of M
if (p==-1) return(solve(A))
# M^0 = I
if (p==0) return(diag(1,dim(A)[1],dim(A)[2]))
# M^1 = M
if (p==1) return(A)
if (p < -1) stop("only powers >= -1 allowed")
if (p != as.integer(p)) stop("only integer powers allowed")
R = A
for (i in 2:p) {
R = R %*% A
}
return(R)
}
mat1<-matrix(c(0.25,0.25,0.25,0.25),nrow=1)
mat2<-matrix(c(0,0,1,0,0.3,0,0.3,0.3,1,0,0,0,0,1,0,0),nrow=4)
mat1%*%t(mpower(mat2,10000))
我得到了
[1,] 0.4996252 0 0.4996252 0
答案 0 :(得分:2)
在MATLAB中做到了这一点:
>> a = [0.25, 0.25, 0.25, 0.25]
a =
0.2500 0.2500 0.2500 0.2500
>> b= [0 0 1 0; .333 0 .333 .333; 1 0 0 0; 0 1 0 0]
b =
0 0 1.0000 0
0.3330 0 0.3330 0.3330
1.0000 0 0 0
0 1.0000 0 0
>> c = b^10000
c =
1.0000 0 0 0
0.4993 0 0.4993 0
0 0 1.0000 0
0.4993 0 0.4993 0
>> a*c'
ans =
0.2500 0.2496 0.2500 0.2496
Java代码正常运行。但是:
>> a*c
ans =
0.4996 0 0.4996 0
因此,您的矩阵会在R代码中转换,因为您的byrow = TRUE
语句中需要as.matrix
。
澄清:
mat2<-matrix(c(0,0,1,0,0.3,0,0.3,0.3,1,0,0,0,0,1,0,0),nrow=4)
创建矩阵
0 0.3 1 0
0 0 0 1
1 0.3 0 0
0 0.3 0 0
你想要
mat2<-matrix(c(0,0,1,0,0.3,0,0.3,0.3,1,0,0,0,0,1,0,0),nrow=4,byrow=TRUE)
创建矩阵
0 0 1 0
0.3 0 0.3 0.3
1 0 0 0
0 1 0 0