choose random places on matrix

1 回表示 (過去 30 日間)
omer
omer 2024 年 8 月 30 日
編集済み: Image Analyst 2024 年 8 月 30 日
i need to create a game of maze on matlab. i have zero matrix mXm and i need to insert to the matrix n places which will mark as obsticals, how can i choose n random places on matrix and replace the zeros to 1? (randomly)

回答 (2 件)

arushi
arushi 2024 年 8 月 30 日
Hi Omer,
  • randperm: This function generates a random permutation of integers from 1 to totalElements, ensuring that the selected indices for obstacles are unique.
Here is an example :
function maze = createMaze(m, n)
% Check if the number of obstacles is less than or equal to total matrix elements
if n > m * m
error('Number of obstacles cannot exceed the total number of matrix elements.');
end
% Initialize the m x m matrix with zeros
maze = zeros(m, m);
% Generate n unique random indices for obstacles
totalElements = m * m;
randomIndices = randperm(totalElements, n);
% Convert linear indices to row and column subscripts
[rowIndices, colIndices] = ind2sub([m, m], randomIndices);
% Place obstacles in the matrix
for i = 1:n
maze(rowIndices(i), colIndices(i)) = 1;
end
end
Hope this helps.

Image Analyst
Image Analyst 2024 年 8 月 30 日
編集済み: Image Analyst 2024 年 8 月 30 日
Simply use randperm and linear indexing. No need to figure out or convert locations to (row, column) indexes (that's a waste of time).
m = 7; % Width and height of maze
maze = false(m, m); % Initialize maze to all zeros. Use logical type to save memory space.
numOnes = round(0.3 * m * m); % 30% of locations will be 1's.
randomLocations = randperm(m * m, numOnes); % Get all locations in a random order.
maze(randomLocations) = 1 % Assign a 1 to those locations.
maze = 7x7 logical array
0 0 1 0 0 0 0 0 0 1 0 1 0 0 1 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0 1 0 0 1 1 0 0 1 0 0 1 1 1 0 0 0

カテゴリ

Help Center および File ExchangeLabyrinth problems についてさらに検索

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by