简体   繁体   中英

Replace certain elements of matrix with elements of another matrix [Matlab / Octave]

I have two matrices:

A = [0,1,1;1,0,0;0,0,0]
B = [3,0,0;0,3,3;4,4,4]

And I want to replace alle the 0-elements in matrix A, with the element, that is on the same position in matrix B.

In the above example the result matrix would look like this:

result = [3,1,1;1,3,3;4,4,4]

Is there a matlab function for that purpose, or do I have to write one on my own?

Regards

This is easily achieved with indexing:

idx = A == 0;
A(idx) = B(idx);

Oneliner solution using logical addressing:

A(A == 0) = B(A == 0);

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