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

Another Matlab Matrix question

  1. Jul 1, 2011 #1
    I am trying to speed up some code I have written in MATLAB, and I yet to get to grips with the whole vectorization thing. Could somebody tell me an efficient way of doing the following:

    I need to create a matrix with zeros along the diagonal and the other elements are either zero or a random number between -1 and 1, in a fixed proportion and randomly placed. e.g. a 5 by 5 matrix with zeros along the diagonal and 40% of the remaining 20 elements are zero and 60% of the remaining elements are between -1 and 1 (doesn't especially matter to me if zero is included in that). If the given proportion of the remaining non-diagonal elements is not an integer, then it should be rounded to the closest integer.

    I have done this already by creating a vector with the correct proportion of zeros and numbers randomly placed, and then used two for loops and an if statement to assign these elements to the non diagonal positions in the matrix. This seems really inefficient and I am sure there is a nice simple way of doing what I want in MATLAB! I have scoured the documentation but can't figure it out.

    Any help would be greatly appreciated
  2. jcsd
  3. Jul 1, 2011 #2


    User Avatar
    Science Advisor

    Welcome to PhysicsForums!

    I don't think there's a single (vectorized) command that can do this all--vectorization is admittedly not my strong suit, but not everything in MATLAB can be vectorized.
  4. Jul 1, 2011 #3
    Perhaps you are correct, but I have been consistently impressed with how Matlab handles matrices in the (short) time I have used it.

    The program I am running is a Monte Carlo type experiment so I have create this matrix tens of thousands of times every run of my model, so any more efficient method than my own would help immensely. The documentation recommends vectorising as much as possible for better speed.

    Basically my method is to create a vector with n(n-1) elements with the correct proportion of random numbers and zeros, which does not seem to resource intensive. My next bit of code feels really clumsy though:

    for counter2=1:n
    for counter3=1:n
    if counter2~=counter3
    Last edited: Jul 1, 2011
  5. Jul 1, 2011 #4
    have you tried the diag() command to help out? I would think rand() in combination with diag() could do most of what you want to do fairly easily.
  6. Jul 2, 2011 #5
    Yes, I have attempted to use diag() in various ways, but I can only set what is on the diagonal with it, or extract the diagonal from a matrix. What I need to do is set the non-diagonal elements of the matrix but can't figure it out without lots of loops.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook