1

Mサイズとの行列が与えられた場合、N合計が特定の値になるように、各行に整数値(> = 0)を入力します。

Mとの寸法はN特定の数式を使用して事前に計算されているため、目的の条件(つまりsum_val以下)が与えられた場合に塗りつぶしに一致することが保証されます。

これは2つの例です

#sum_val <-2
#m<-6
#n<-3

# the value of "sum_val" may vary
# and 'm' 'n' also change depends on it

# First are initialized using 0
#mat <- matrix(0,nrow=m,ncol=n);


# Below results are hand coded:
       [,1] [,2] [,3]
[1,]    1    1    0   # Sum of each rows here is equal to 'sum_val = 2'
[2,]    1    0    1
[3,]    0    1    1
[4,]    2    0    0
[5,]    0    2    0
[6,]    0    0    2

もう一つの例:

> sum_val<-2;
#m<-15
#n<-5
#mat <- matrix(0,nrow=m,ncol=n);

# Below results are hand coded:
       [,1] [,2] [,3] [,4] [,5]
 [1,]    1    1    0    0    0   # rows also sums up to 2 
 [2,]    1    0    1    0    0
 [3,]    1    0    0    1    0
 [4,]    1    0    0    0    1
 [5,]    0    1    0    0    1
 [6,]    0    0    1    0    1
 [7,]    0    0    0    1    1
 [8,]    0    1    0    1    0
 [9,]    0    1    1    0    0
[10,]    0    0    1    1    0
[11,]    2    0    0    0    0
[12,]    0    2    0    0    0
[13,]    0    0    2    0    0
[14,]    0    0    0    2    0
[15,]    0    0    0    0    2

私は次のループで立ち往生しています:

> for (ri in 1:m) {
+     for (ci in 1:n) {
+      
+        
+        # Not sure how to proceed from here
+        if(ci==2) {
+             mat[ri,ci] <- 1;
+        }
+     }
+ }

それを解決するための最良の方法は何ですか?

4

1 に答える 1

6

これが私がそれを解決する方法です!

library(partitions)

sum_val <- 2
n <- 5

t(as.matrix(compositions(sum_val, n)))
      [,1] [,2] [,3] [,4] [,5]
 [1,]    2    0    0    0    0
 [2,]    1    1    0    0    0
 [3,]    0    2    0    0    0
 [4,]    1    0    1    0    0
 [5,]    0    1    1    0    0
 [6,]    0    0    2    0    0
 [7,]    1    0    0    1    0
 [8,]    0    1    0    1    0
 [9,]    0    0    1    1    0
[10,]    0    0    0    2    0
[11,]    1    0    0    0    1
[12,]    0    1    0    0    1
[13,]    0    0    1    0    1
[14,]    0    0    0    1    1
[15,]    0    0    0    0    2
于 2012-05-11T03:10:40.023 に答える