pythonarraysnumpymatrix

How can I set a specific value on an array (matrix) of booleans per True/False without using loops in python?


I am trying to make two random generated matrices mat1 and mat2 with random integer values between 0, 255 and check which cells are equal.

and I know this much

import numpy as np

mat1 = np.random.randint(0, 255, size=(1000,1000))
mat2 = np.random.randint(0, 255, size=(1000,1000))
mat_compare = (mat1 == mat2)

I wanted to know how to set True cells to an integer value of 255 and False cells to 0 in another array type valuable. I tried this much but it only detected 255 and 0 as booleans:

mat_compare[(mat1 == mat2)] = 255
mat_compare[(mat1 != mat2)] = 0

print(mat_compare)

and the results ended up as:

[[False False False ... False False False]
 [False False False ... False False False]
 [False False False ... False False False]
 ...
 [False False False ... False False False]
 [False False False ... False False False]
 [False False False ... False False False]]

and just to note again that I expect it to use no for loops at all. Thanks.


Solution

  • You can simply run

    mat_compare*255
    

    which gives for example

    array([[  0,   0,   0, ...,   0,   0,   0],
           [  0,   0,   0, ...,   0,   0,   0],
           [  0,   0,   0, ...,   0,   0,   0],
           ...,
           [  0,   0,   0, ...,   0,   0,   0],
           [  0,   0,   0, ...,   0,   0,   0],
           [255,   0,   0, ...,   0,   0,   0]])