27

I want to create a tensor only containing boolean values. In Matlab that would be

a = false(10,1)
1
  • 1
    Since version 1.2.0 PyTorch supports boolean tensors. Commented Aug 16, 2019 at 11:10

3 Answers 3

40

Isn't this more economical (albeit longer):

a = torch.zeros(10, dtype=torch.bool)

or, in older versions,

a = torch.zeros(10, dtype=torch.uint8)

(Thanks @drevicko for the pointer to bool.)

Sign up to request clarification or add additional context in comments.

2 Comments

There's now a torch.bool type you can (should?) use.
@drevicko indeed, for instance torch.where(cond,a,b) will print a deprecated warning if cond is of type ByteTensor. You can conveniently use .type(torch.bool) to avoid the warning: cond.type(torch.bool).
9

Already found it:

a = torch.zeros(10)
b = a.type(torch.ByteTensor)

3 Comments

A shorter version of this: torch.zeros(10).byte().
Pytorch now has torch.bool. Please use that instead of torch.ByteTensor.
obsolete answer. how can one get obsolete answers unaccepted?
1

You can use torch.full to create a tensor with any arbitrary value, including booleans:

torch.full((20, 15), True)
torch.full((20, 15), False)

Or, you can use torch.ones or torch.zeros by specifying the torch.bool data type:

torch.ones((20, 15), dtype=torch.bool) # True
torch.zeros((20, 15), dtype=torch.bool) # False

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.