Generating NxN Matrix with Random 0s and 1s - MATLAB M File Help

AI Thread Summary
Generating an NxN matrix filled with 25% random 0s and 1s in MATLAB is possible using random number generation and logical indexing. To create the matrix, one can generate a random matrix of the desired size, threshold it to achieve the 25% filling, and then shuffle the elements. Additionally, selecting a 3x3 sub-matrix centered around a specific point can be done through appropriate indexing of the array. The discussion highlights the need for assistance with both generating the random matrix and extracting the sub-matrix.
shawaj
Messages
3
Reaction score
0
i am writing a MATLAB m file.

i need to generate a NxN matrix 25% filled with 0s and 1s in a random pattern...

is this at all possible?

also, in an NxN matrix, i need to select a 3x3 matrix centered around a certain point, can you help me out with this?

many thanks for your help
 
Physics news on Phys.org
shawaj said:
also, in an NxN matrix, i need to select a 3x3 matrix centered around a certain point, can you help me out with this?

many thanks for your help

Isn't this just a question of indexing the array appropriately? I don't remember MATLAB syntax exactly, but often in these computational languages, indexing of an array is achieved by means of square brackets [] or parentheses (). So if your array is called 'arr' and the point of interest is at column i, row j (or vice versa, depending on the convention), you would index it as arr[i,j]. Now you just need to range from i-1 to i+1 and from j-1 to j+1. I don't remember what MATLAB uses to mean "range from", but it might be something like a:b to mean "range from a to b" with the colon replaced by whatever symbol MATLAB uses for this purpose. Then your 3x3 sub-array would be given by arr[i-1:i+1, j-1:j+1].
 
I will try that out!

Any ideas on the other one? Generating a random matrix of 0s and 1s?
 
many thanks for your help...cepheid

wasn't exactly what i was looking for but it helped me to find what i was looking for and have sorted that part of it now.

still trying to work out how to generate the random matrix as detailed above
 
Back
Top