How to place 2 numbers on a matrix randomly but besides each other
1 view (last 30 days)
Show older comments
Hi all
I have a 10*10 matrix and i want to place 2 (two's) randomly on that matrix but they must always be besides each other
i need to do this for 3,4,5 where i need to place 3(three's) randomly on the matrix but besides each other and 4(fours) besides each other etc....
how do i do this?
i need to add these numbers on this matrix
BSgrid=zeros(10);
thanks in advance
0 Comments
Answers (1)
Image Analyst
on 10 Mar 2020
Use randi() to get a random location inside the matrix, then place the other 2 next to it.
Try this and adapt as needed:
m = zeros(10, 10) % Whatever your original matrix is.
[rows, columns] = size(m)
randomRow = randi([2, rows-1], 1)
randomCol = randi([2, columns-1], 1)
direction = randi(8, 1)
% Assign initial 2
m(randomRow, randomCol) = 2;
% Assign the additional 2 in one of the 8 surrounding pixels.
switch direction
case 1
m(randomRow-1, randomCol-1) = 2;
case 2
m(randomRow-1, randomCol) = 2;
case 3
m(randomRow-1, randomCol+1) = 2;
case 4
m(randomRow, randomCol-1) = 2;
case 5
m(randomRow, randomCol-1) = 2;
case 6
m(randomRow+1, randomCol-1) = 2;
case 7
m(randomRow+1, randomCol) = 2;
case 8
m(randomRow+1, randomCol+1) = 2;
end
m
2 Comments
Image Analyst
on 18 Mar 2020
Edited: Image Analyst
on 19 Mar 2020
Well first you want to assign a random row don't you. So we need to get a random row and a random column. But because I want to allow for a neighbor that is anywhere around it (in the 8 neighboring elements), I can't go from the first to the last. I can only go from the second to the next to the last (which is indicated by end-1). So I get those and then assign it:
% Assign initial 2
m(randomRow, randomCol) = 2;
Next I need to get a neighbor for that in one of the 8 elements surrounding that random location. And I don't want to always pick the location to the right of it of course. I want to be able to pick ANY of the 8 locations to place the neighbor. So I get a random integer from 1 to 8, indicating which direction, from the one I already placed, the new one should be placed. So I need to assign it somewhere in the range of (randomRow - 1) to (randomRow + 1) for the row, and similar for the column: (randomCol - 1) to (randomCol + 1) for the column. So direction is a random number from 1 to 8 and the switch statement will go into the case that matches the number it is. Then, inside the case, I assign the second "2" to the proper location. Note that each case is in a different location with respect to the one I already placed.
Tarek, if this worked, could you please "Accept this answer"? Thanks in advance.
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!