简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM