Results 1 to 19 of 19

Thread: Random Binary Matrix

  1. #1

    Thread Starter
    New Member
    Join Date
    Oct 2015
    Posts
    11

    Random Binary Matrix

    Hello Everyone. I would like to create a random binary matrix ( only 0 and 1) of any size of row and column in vb.net. I am not getting any suitable code for that. Any help will be highly appreciable.
    Regards.
    Tariq

  2. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    36,960

    Re: Random Binary Matrix

    Well, the straightforward approach would look something like this:
    Code:
    Private mRand as New Random
    Private rndMatrix as Integer(,)
    
    Public Sub BuildMatrix(rows as integer, columns as integer)
     Redim rndMatrix(rows,columns)
    
     For x=0 to rows
      For y=0 to columns
        rndMatrix(x,y)=mRand.next(0,2)
      Next
     Next
    End Sub
    Last edited by Shaggy Hiker; May 1st, 2019 at 02:48 PM. Reason: Fixed the error in the code, as noted by Si.
    My usual boring signature: Nothing

  3. #3

    Thread Starter
    New Member
    Join Date
    Oct 2015
    Posts
    11

    Re: Random Binary Matrix

    In MATLAB "randi([0 1], 5,5)" command generates 5 x 5 binary matrix. But i am not finding any suitable code for creating random binary matrix in vb.net

  4. #4

    Thread Starter
    New Member
    Join Date
    Oct 2015
    Posts
    11

    Re: Random Binary Matrix

    Quote Originally Posted by Shaggy Hiker View Post
    Well, the straightforward approach would look something like this:
    Code:
    Private mRand as New Random
    Private rndMatrix as Integer(,)
    
    Public Sub BuildMatrix(rows as integer, columns as integer)
     Redim rndMatrix(rows,columns)
    
     For x=0 to rows
      For y=0 to columns
        rndMatrix=mRand.next(0,2)
      Next
     Next
    End Sub
    Thanks Hiker for your quick reply. But the error says..
    Code:
     rndMatrix = mRand.Next(0, 2)
    The value of type Interger can not be converted to Integer (*,*)

  5. #5
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,777

    Re: Random Binary Matrix

    That is easy to fix:
    Code:
        rndMatrix(x,y) = mRand.next(0,2)

  6. #6
    Fanatic Member kpmc's Avatar
    Join Date
    Sep 2017
    Posts
    1,012

    Re: Random Binary Matrix

    Shaggy, do you reckon he should put a seed? Otherwise every time your code runs, would it not product exactly the same random result?
    Code:
    Private mRand As New Random(Now.Millisecond)

  7. #7
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,436

    Re: Random Binary Matrix

    Quote Originally Posted by kpmc View Post
    Shaggy, do you reckon he should put a seed? Otherwise every time your code runs, would it not product exactly the same random result?
    Code:
    Private mRand As New Random(Now.Millisecond)
    Sounds like you're thinking of VB6.
    Did you try it in .net. I don't think you'll get the "same random result".

  8. #8
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    36,960

    Re: Random Binary Matrix

    No, that's an issue for all random number generators. They all get seeded. In VB6, that seeding was done quite deliberately, and often quite incorrectly (I found that one out the hard way).

    In this case, you are safe as long as there is only one instance of the class. Had I made the random number generator a local variable, then the problem would show up if you ran the function in a tight loop. By making the Random at form scope, it will use the system time as a seed, by default. As long as two of those classes aren't created within the same second, each would produce an independent sequence. Calling the function repeatedly will also create independent sequences, so it's safe.

    However, seeding with the time is not really safer. The main reason why you can seed random number generators explicitly, like that, is so that you can guarantee the same sequence over and over for testing purposes. Otherwise, you want to seed with some fairly unique number, so the system time is used. In other words, deliberately seeding with the system time is doing what the default would have done anyways, so it may just trick you into thinking that it's safer when it is not.

    Having said that, back in VB6 times, the seed was the system time in seconds, so you'd have issues if you re-Randomize (Randomize was the function that seeded the generator) within the same second. That's an odd choice when you have milliseconds available. I haven't gone looking to see if the .NET Random object seeds with the millisecond or the second. If it's the millisecond, that would....well, I was going to say that would be better, but it probably would not. The odds of accidentally creating two Random objects in the same second is certainly better than creating two in the same millisecond, but if you make a mistake (like leaving the (x,y) out of an example), it's better if it is caught quickly. If the seeding is by millisecond, that would behave like a race condition. A mistake might work correctly (by accident) most of the time, and only occasionally fall into non-randomness.
    My usual boring signature: Nothing

  9. #9
    Fanatic Member kpmc's Avatar
    Join Date
    Sep 2017
    Posts
    1,012

    Re: Random Binary Matrix

    Did you try it in .net
    I have used random in vb.net and without seeding a random int my results were always the same random result

    For example, place all letters of alphabet into a CharArray, write a random routine without a seed that generates a random set of chars from the array index. If your results are like mine itll be the same random chars every time.

  10. #10
    Fanatic Member kpmc's Avatar
    Join Date
    Sep 2017
    Posts
    1,012

    Re: Random Binary Matrix

    Quote Originally Posted by Shaggy Hiker View Post
    No, that's an issue for all random number generators. They all get seeded. In VB6, that seeding was done quite deliberately, and often quite incorrectly (I found that one out the hard way).

    In this case, you are safe as long as there is only one instance of the class. Had I made the random number generator a local variable, then the problem would show up if you ran the function in a tight loop. By making the Random at form scope, it will use the system time as a seed, by default. As long as two of those classes aren't created within the same second, each would produce an independent sequence. Calling the function repeatedly will also create independent sequences, so it's safe.

    However, seeding with the time is not really safer. The main reason why you can seed random number generators explicitly, like that, is so that you can guarantee the same sequence over and over for testing purposes. Otherwise, you want to seed with some fairly unique number, so the system time is used. In other words, deliberately seeding with the system time is doing what the default would have done anyways, so it may just trick you into thinking that it's safer when it is not.

    Having said that, back in VB6 times, the seed was the system time in seconds, so you'd have issues if you re-Randomize (Randomize was the function that seeded the generator) within the same second. That's an odd choice when you have milliseconds available. I haven't gone looking to see if the .NET Random object seeds with the millisecond or the second. If it's the millisecond, that would....well, I was going to say that would be better, but it probably would not. The odds of accidentally creating two Random objects in the same second is certainly better than creating two in the same millisecond, but if you make a mistake (like leaving the (x,y) out of an example), it's better if it is caught quickly. If the seeding is by millisecond, that would behave like a race condition. A mistake might work correctly (by accident) most of the time, and only occasionally fall into non-randomness.
    I think I follow, and I've been down this road. I have argued that the best way to get a seed would be to pull numbers from a GUID within the Seed bounds, which I dont remember off hand.

  11. #11
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    36,960

    Re: Random Binary Matrix

    I really expected somebody to come up with a better answer than mine in the intervening time. That loop just doesn't seem all that efficient, to me, and it seems like there ought to be something better. This is about all I could come up with, though, and it only works for matrices smaller than 31x31:
    Code:
    Private mRand as New Random
    Private rndMatrix as Integer(,)
    
     Public Sub BuildMatrix(rows As Integer, columns As Integer)
            ReDim rndMatrix(rows, columns)
            For x = 0 To rows
                Dim valu = mRand.Next(0, Integer.MaxValue)
                For y = 0 To columns
                    rndMatrix(x, y) = ((valu >> y) And &H1)
                Next
            Next
        End Sub
    I didn't add the extra code needed to ensure that the arguments were small enough, though that would be easy enough to do. What else can folks come up with?

    What this does is greatly reduces the number of calls to .Next, which probably enhances performance.
    My usual boring signature: Nothing

  12. #12
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    36,960

    Re: Random Binary Matrix

    Quote Originally Posted by kpmc View Post
    I think I follow, and I've been down this road. I have argued that the best way to get a seed would be to pull numbers from a GUID within the Seed bounds, which I dont remember off hand.
    A random seed shouldn't be superior to any other seed, which is why the system time is used. As long as two Random objects get different seeds, there shouldn't be any correlation between their sequences...in theory. However, there is also a more robust random number generator offered up in System.Security.Cryptography. Presumably, the performance of the cryptographically secure random number generator is considerably less than the common form, or else there wouldn't be two.
    My usual boring signature: Nothing

  13. #13
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,419

    Re: Random Binary Matrix

    Quote Originally Posted by kpmc View Post
    For example, place all letters of alphabet into a CharArray, write a random routine without a seed that generates a random set of chars from the array index. If your results are like mine itll be the same random chars every time.
    I must be misunderstanding...
    Code:
        Private Shared prng As New Random 'no seed
        Private letters As String = "abcdefghijklmnopqrstuvwxyz"
        Private rslts As New List(Of String)
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            rslts.Clear()
            For x As Integer = 1 To 5
                rslts.Add(RandomSetChars)
            Next
            Stop 'examine rslts
        End Sub
    
        Private Function RandomSetChars() As String
            Dim rv As New System.Text.StringBuilder
            For x As Integer = 1 To 5
                rv.Append(letters(prng.Next(letters.Length)))
            Next
            Return rv.ToString
        End Function
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  14. #14
    Fanatic Member kpmc's Avatar
    Join Date
    Sep 2017
    Posts
    1,012

    Re: Random Binary Matrix

    I must be misunderstanding...
    As with what Shaggy was explaining, assuming if you created the Random local to the function, perhaps then you would see the results I was referring.

  15. #15
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    36,960

    Re: Random Binary Matrix

    Yes. If you create it local to the function, and call the function in the loop, or create Random objects in a loop, then you'll get the same value over and over...until the system time advances by one second, at which point you'll switch to a new repeating value. It's a truly horrific way to time your code if you are looking for a really bad way to time code.
    My usual boring signature: Nothing

  16. #16
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,436

    Re: Random Binary Matrix

    Quote Originally Posted by kpmc View Post
    As with what Shaggy was explaining, assuming if you created the Random local to the function, perhaps then you would see the results I was referring.
    I wouldn't assume that you would create the Random function local to the function for two reasons.
    1. You were referring to Shaggy's code when you asked the question and Shaggy's code didn't create the instance local to the function.
    2. No one that I know of would recommend creating the instance local to a function.

  17. #17

    Thread Starter
    New Member
    Join Date
    Oct 2015
    Posts
    11

    Re: Random Binary Matrix

    Thanks Shaggy, geek, kmpc and all for such educative discussion. It solved my problem. Thanks Again.

  18. #18
    Fanatic Member kpmc's Avatar
    Join Date
    Sep 2017
    Posts
    1,012

    Re: Random Binary Matrix

    Quote Originally Posted by passel View Post
    I wouldn't assume that you would create the Random function local to the function for two reasons.
    1. You were referring to Shaggy's code when you asked the question and Shaggy's code didn't create the instance local to the function.
    2. No one that I know of would recommend creating the instance local to a function.
    Not sure what youre trying to get at here. The point is I wasnt quite sure how the class worked, so I asked. So if youre trying to elaborate on the fact I didnt know something, great work!

  19. #19
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,419

    Re: Random Binary Matrix

    Quote Originally Posted by kpmc View Post
    Not sure what youre trying to get at here. The point is I wasnt quite sure how the class worked, so I asked. So if youre trying to elaborate on the fact I didnt know something, great work!
    Don't read too much into it. I have classes that have a random for use by the class. In a class it would look like

    Code:
    Public Class Form1
        Private rslts As New List(Of String)
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            rslts.Clear()
            For x As Integer = 1 To 5
                rslts.Add(SomeRand.RandomSetChars)
            Next
            Stop 'examine rslts
        End Sub
    End Class
    
    Public Class SomeRand
    
        Private Shared prng As New Random 'no seed
        Private Shared ReadOnly letters As String = "abcdefghijklmnopqrstuvwxyz"
    
        Public Shared Function RandomSetChars() As String
            Dim rv As New System.Text.StringBuilder
            For x As Integer = 1 To 5
                rv.Append(letters(prng.Next(letters.Length)))
            Next
            Return rv.ToString
        End Function
    
    End Class
    Last edited by dbasnett; May 3rd, 2019 at 08:02 AM.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width