- #1
rt1870
- 3
- 0
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
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