can a random number generator be used in a matrix?

3 次查看(过去 30 天)
I'm trying to make a minesweeper game in matlab so I set up a matrix A=zeros(10) and I wanted to know if I could write the code so that 1s will be randomly scattered throughout the matrix whenever the code is run.

采纳的回答

Star Strider
Star Strider 2021-12-9
The randi function would be good for that, and thresholding the rand function would also work.
M = randi([0 1],10)
M = 10×10
1 1 1 0 1 1 1 1 1 0 1 0 1 0 0 1 0 1 0 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 0 0 0 1 0 0 1 0 0 1 1 0 1 1 0 0 1 0 0 0 0 1 1 0 0 1 0 1 1 1 0 1 0 1 0 1 1 1 1 0 0 0 1 0 0 0 1 1 0 1 1 0 0 1 1 1 0 0 1 1 1 1 1 0
M = +(rand(10)>=0.5)
M = 10×10
0 0 1 1 0 1 0 1 0 0 0 1 1 0 1 1 1 1 1 1 0 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 1 1 1 1 0 1 1 1 1 1 1 1 0 0 1 0 1 1 1 1 0 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 0 0 1 1 1 1 1 0 0 0 1 0 0 1 0 0 1 1 1 0 1
Experiment to get appropriate results.
.
  3 个评论
Steven Lord
Steven Lord 2021-12-9
Do you want a certain probability of each cell being a mine or do you want a certain fixed number of mines? In the latter case, use randperm to identify a few locations where the mines are located then fill in those locations with linear indexing.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Random Number Generation 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by