Adam
Adam

Reputation: 10016

Conditionally replacing values in a matrix

Say I have two matrices A = [ 1 0 0 1 ] and B = [ 9 9 7 6 ].

If A(i) != 0 I want to replace B(i) with A(i). Is there a built in function in Matlab that can do this? I don't want to use loops.

Upvotes: 0

Views: 90

Answers (1)

Robert Seifert
Robert Seifert

Reputation: 25232

It is as simple as that:

B(A ~= 0) = A(A ~= 0) 

In Matlab not equal has the operator ~= as you could have found out in the documentation. And you should learn some basics about matrix indexing, in this case especially logical indexing.

Upvotes: 7

Related Questions