Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Matlab help!

  1. Mar 13, 2010 #1
    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
  2. jcsd
  3. Mar 13, 2010 #2


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    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].
  4. Mar 13, 2010 #3
    I will try that out!

    Any ideas on the other one? Generating a random matrix of 0s and 1s?
  5. Mar 13, 2010 #4
    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
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook