How to replace the non zero values of a matrix with another value?

Illustration
John D'Errico - 2023-04-28T11:39:50+00:00
Question: How to replace the non zero values of a matrix with another value?

How to replace the non zero values of a matrix with another value?   If there is a matrix 5*5 and it contains zero values, how can I keep the zero values and replace the non zero value with 0.1?   in matlab version R2018a

Expert Answer

Profile picture of Kshitij Singh Kshitij Singh answered . 2025-11-20

A(A ~= 0) == 0.1;
One line of code. That applies to ANY release of MATLAB. As far back as I have been using MATLAB, so only back about 35 years or so.
 
And of course, there are other equally simple ways to solve it. For example:
 
 
A = (A ~= 0)*0.1;

 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!