Matlab

How to Find and Replace Values in Matrix in MATLAB

Matrices are the building blocks in MATLAB and are utilized in many applications of science and engineering. MATLAB supports many matrix operations. One of these operations is finding and replacing the values of a matrix.

In this article, we will explore how to find and replace the elements of a matrix in MATLAB using multiple examples.

How to Find and Replace the Elements of a Matrix in MATLAB?

When we deal with large matrices such as a matrix having a 1000-by-1000 size, it becomes very difficult to find and replace a value from that matrix. MATLAB provides us with a suitable solution to this problem. In MATLAB, we can find and replace one or more elements by writing a simple MATLAB code. This MATLAB code can be written by using the given steps:

  • Initialize a matrix A with the desired values.
  • Use the find() function by specifying a condition to find the index of the element which you need to replace. The find() function will return the column vector B containing an index of the searched element.
  • Use the A(B) function by assigning it a replacement value. This function will generate a new matrix that will contain replaced values.

Examples

Consider some examples to understand how to find and replace a matrix value in MATLAB.

Example 1

In this example, we initialize a matrix using magic() function and use the find() function that returns the indices of non-zero elements in the matrix A. After that, we replace all non-zero entries of A with 1’s using the ones() function.

A = magic(3)

B = find(A);

A(B) = ones(3)

The obtained output is displayed on the screen.

Example 2

This MATLAB code initializes a matrix using the randi() function and uses the find() function that returns the indices of element 3 in matrix A. After that, we replace the value 3 with the value 5.

A = randi(3,3)

B = find(A==3);

A(B) = 5

Conclusion


Matrices are the building blocks in MATLAB and are utilized in many applications of science and engineering. MATLAB supports many matrix operations including finding and replacing the values of a matrix. In this guide, we define some steps from which we can find and replace the elements of a matrix in MATLAB.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.