can a random number generator be used in a matrix?

조회 수: 3 (최근 30일)
Aidan Palermo
Aidan Palermo 2021년 12월 9일
댓글: Star Strider 2021년 12월 9일
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.
Star Strider
Star Strider 2021년 12월 9일
@Aidan Palermo — As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (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