tensor creation
2D arrays
programming
ones and zeros
data structures

How to create a 2D tensor of Ones and Zeros like so

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Creating a 2D tensor of ones and zeros is one of the most common setup steps in numerical code. You might need it for a mask, a toy example, an adjacency matrix, or a model input template. The main question is not only how to create the matrix, but whether you want all ones, all zeros, or a specific pattern.

Start With the Basic Building Blocks

In Python libraries, the core creation functions are usually named zeros and ones. In NumPy:

python
1import numpy as np
2
3zeros = np.zeros((3, 4), dtype=int)
4ones = np.ones((3, 4), dtype=int)
5
6print(zeros)
7print(ones)

That produces two-dimensional arrays with shape (3, 4).

In PyTorch, the pattern is almost identical:

python
1import torch
2
3zeros = torch.zeros((3, 4), dtype=torch.int64)
4ones = torch.ones((3, 4), dtype=torch.int64)
5
6print(zeros)
7print(ones)

So if your target is simply “a 2D tensor full of zeros” or “a 2D tensor full of ones,” these built-in constructors are the cleanest answer.

Build a Specific Ones-and-Zeros Pattern

Many real questions mean “a 2D tensor containing both ones and zeros in some arrangement.” The easiest way to create a pattern is often to start with zeros and then write ones into selected positions.

NumPy example:

python
1import numpy as np
2
3matrix = np.zeros((4, 5), dtype=int)
4matrix[1, 2] = 1
5matrix[2, 3] = 1
6matrix[3, 0] = 1
7
8print(matrix)

PyTorch example:

python
1import torch
2
3matrix = torch.zeros((4, 5), dtype=torch.int64)
4matrix[1, 2] = 1
5matrix[2, 3] = 1
6matrix[3, 0] = 1
7
8print(matrix)

This approach is simple and works well when you know the positions that should be active.

Create Structured Patterns

Some patterns come up so often that it is better to build them with a vectorized expression rather than by assigning each cell by hand.

For example, an identity-style matrix:

python
1import numpy as np
2
3identity = np.eye(4, dtype=int)
4print(identity)

Or in PyTorch:

python
1import torch
2
3identity = torch.eye(4, dtype=torch.int64)
4print(identity)

You can also create triangular masks. Upper-triangular in NumPy:

python
1import numpy as np
2
3mask = np.triu(np.ones((4, 4), dtype=int))
4print(mask)

These specialized constructors are usually clearer than filling values with loops.

Generate a Pattern From Conditions

Another powerful approach is to compute ones and zeros from a logical condition. Suppose you want ones where the column index is greater than or equal to the row index:

python
1import numpy as np
2
3rows, cols = np.indices((4, 4))
4matrix = (cols >= rows).astype(int)
5
6print(matrix)

This style is especially useful for masks, attention matrices, or coordinate-based patterns in machine learning and scientific computing.

The same idea works in PyTorch:

python
1import torch
2
3row_idx = torch.arange(4).unsqueeze(1)
4col_idx = torch.arange(4).unsqueeze(0)
5matrix = (col_idx >= row_idx).to(torch.int64)
6
7print(matrix)

Why Dtype Matters

By default, some libraries create these arrays as floating-point values. That may be fine for neural networks, but not always for indexing or logical work.

For example:

python
1import numpy as np
2
3matrix = np.ones((2, 2))
4print(matrix.dtype)  # float64

If you really want integer zeros and ones, specify dtype=int or the framework-specific integer type.

Likewise, if the tensor is going into a neural network model, float values may be the correct choice:

python
import torch

mask = torch.ones((2, 2), dtype=torch.float32)

The right dtype depends on what the tensor will be used for next.

Common Pitfalls

The biggest pitfall is building a tensor with Python lists and loops when the library already provides zeros, ones, eye, and conditional vectorized operations. The built-in tensor functions are shorter, faster, and clearer.

Another common issue is using the wrong dtype. Integer masks, Boolean masks, and floating-point tensors each behave differently in later operations.

People also sometimes confuse shape order. A tensor shape of (rows, cols) is not the same as (cols, rows), and the error may not be obvious until later calculations look wrong.

Finally, if the pattern is regular, avoid manual cell-by-cell assignment. Expressions based on indexing or built-in constructors are easier to verify and much less error-prone.

Summary

  • Use zeros or ones for full matrices of a single value.
  • Start with zeros and assign selected cells when only a few positions should be one.
  • Use helpers such as eye or conditional expressions for structured patterns.
  • Choose the dtype deliberately based on whether the tensor is numeric, logical, or model input.
  • Prefer vectorized tensor operations over manual nested loops.

Course illustration
Course illustration

All Rights Reserved.