【问题标题】:simulating n matrix samples with plots用图模拟 n 个矩阵样本
【发布时间】:2016-02-04 15:11:56
【问题描述】:

我想创建一个函数,允许用户选择一个 nxn 矩阵,用 0 和 1 的样本填充它,查找 TIC TAC TOE“获胜”(所有 1 或 0 连续、col 或 diag ),并仅基于随机样本绘制获胜解决方案的概率图。我希望用户能够根据需要运行尽可能多的模拟。

我已经有一个用于创建单个矩阵的代码

ranmat = function(nrow,ncol){
matrix(sample(c(0,1),replace=T,size=nrow*ncol),nrow=nrow)

我也有关于如何检查胜利的想法,但我不知道如何运行模拟 n 次。

【问题讨论】:

  • 你也可以添加检查胜利的代码吗?
  • 一个,顺便欢迎使用stackoverflow :-)
  • 当然……我的检查胜利的代码……function (game) { if(any(colSums(game)==3,colSums(game)==0,rowSums(game) )==3, rowSums(game)==0,sum(diag(game))==3,sum(diag(game))==0, sum(diag(apply(game,2,rev)))= =3,sum(diag(apply(game,2,rev)))==0)) {return("YUP")} else{return("NOPE")} } ## 'yup' 和 'nope'如果有任何赢家

标签: r matrix


【解决方案1】:

我认为您正在寻找 for 循环?我认为有很多方法可以做你想做的事。

# 1st option: you might want to call your function n times:
# with l,k and n being integer values (n is the number of simulation)
for(i in 1:n) ranmat(nrow=k,ncol=l) 

# 2nd option: you tell your function how often you want to simulate:
ranmat = function(nrow,ncol,nsimult){
    for(i in 1:nsimult){
        # your simulations
    }
    return(result) # with result being an appropriate way to return the outcome of your simulations
}
ranmat(nrow=k,ncol=l,nsimult=n) #call to your function with k,l and n being integer values

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多