我有一个权重向量,我想在对称矩阵中插入。我想要权重的所有组合(所有位置的所有权重,但对角线都没有)
我尝试遍历矩阵,但随后我只得到相同的矩阵三次。 (而且我也找不到它的答案或对此问题的公开解决方案。)
weight <- seq(0.1, 1, by = 0.1)
C <- matrix(0, nrow = 3, ncol = 3)
for (i in seq_len(nrow(C))) {
C_old <- C
for (j in seq_len(i)) {
if (i == j) {
C[i, i] <- 0
} else {
C_old2 <- C_old
for (w in weight) {
C[i, j] <- w
C[j, i] <- C[i, j]
C_old[i, j] <- w
C_old[j, i] <- C_old[i, j]
C_old2[i, j] <- w
C_old2[j, i] <- C_old2[i, j]
iter <- iter + 3
print(C)
print(C_old)
print(C_old2)
}
}
}
我想拥有所有这样的矩阵
Matrix 0:
0 0 0
0 0 0
0 0 0
Matrix 1:
0 0 0
0 0 0.1
0 0.1 0
Matrix 2:
0 0 0.1
0 0 0.1
0.1 0.1 0
Matrix 3:
0 0.1 0.1
0.1 0 0.1
0.1 0.1 0
Matrix 4:
0 0.1 0.1
0.1 0 0.2
0.1 0.2 0
Matrix n:
0 0.9 0.1
0.5 0 0.5
0.1 0.9 0
Matrix:
0 x y
z 0 z
y x 0
我希望最后一个矩阵的所有组合均为x,y和z可以是任意权重值。
第一个矩阵(全为0)并不是很重要,因此,如果解决方案省略了,我不在乎
答案 0 :(得分:1)
不知道您想要什么,但是在这里:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="App" ng-controller="main">
<div>
<label>Quantity</label>
<input type="text" ng-model="detail.qty" ng-change="updateTotal()">
</div>
<div>
<label>Price</label>
<input type="text" ng-model="detail.price" ng-change="updateTotal()">
</div>
<div>
<label>Discount (%)</label>
<input type="text" ng-model="detail.discount" ng-change="updateTotal()">
</div>
<div>
<label>Total</label>
<input readonly type="text" ng-model="detail.total">
</div>
</div>
结果:
weight <- seq(0.1, 1, by = 0.1)
C <- matrix(0, nrow = 3, ncol = 3)
C_list <- vector("list", 10)
for(i in 1:length(weight)){
for(j in 1:3){
if(j == 1){
C[2,3] <- weight[i]
C[3,2] <- weight[i]
}
if(j == 2){
C[1,3] <- weight[i]
C[3,1] <- weight[i]
}
if(j == 3){
C[1,2] <- weight[i]
C[2,1] <- weight[i]
}
C_list[[i]][[j]] <- C
}
}
...
答案 1 :(得分:1)
多亏了LAP,我改变了方法,并设法做到这一点:
weight <- seq(0.1, 1, by = 0.1)
C <- matrix(0, nrow = 3, ncol = 3)
C_list <- vector("list", 10)
names(C_list) <- as.character(weight)
for(i1 in weight){
C_list[[as.character(i1)]] <- vector("list", 10)
names(C_list[[as.character(i1)]]) <- as.character(weight)
for (i2 in weight){
C_list[[as.character(i1)]][[as.character(i2)]] <- vector("list", 10)
names(C_list[[as.character(i1)]][[as.character(i2)]]) <- as.character(weight)
for (i3 in weight) {
C[2, 3] <- i1
C[3, 2] <- i1
C[1, 3] <- i2
C[3, 1] <- i2
C[1, 2] <- i3
C[2, 1] <- i3
C_list[[as.character(i1)]][[as.character(i2)]][[as.character(i3)]] <- C
}
}
}
现在,C_list是一个列表列表的列表,每个列表都有一个矩阵。 length(unlist(unlist(C_list, recursive = FALSE), recursive = FALSE)) == 1000
是存在的10 ^ 3组合。