MATLAB Answers

How to swap array element from two arrays conditionally

8 views (last 30 days)
Ted Baker
Ted Baker on 4 Dec 2019
Commented: Ted Baker on 4 Dec 2019
I'm looking to plot a matrix using data from two arrays. If the second array has a number which is not zero in an element, this element is moved into the first array. I have seen how this might be done using deal(), but I would like to avoid using a loop with if statement for performance reasons. Is there a convenient way of doing this?
An example of this is follows, with arrays A, B and C ( the result);
Array.png

  0 Comments

Sign in to comment.

Accepted Answer

Akira Agata
Akira Agata on 4 Dec 2019
By using indexing technique, you can simply do this kind of task.
The following is an example:
% Original matrixes
A = [...
0 1 1 1 0 0;...
0 0 0 0 0 0;...
0 0 0 0 0 0];
B = [...
0 3 0 0 4 0;...
0 2 0 0 2 0;...
0 0 0 0 0 0];
% Creating C by using index
idx = B ~= 0;
C = A;
C(idx) = B(idx);

  1 Comment

Ted Baker
Ted Baker on 4 Dec 2019
Thank you very much for introducing me to the technique, along with a very clear example. It now works perfectly in my application. :)

Sign in to comment.

More Answers (1)

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH on 4 Dec 2019
C=A;
C(B~=0)=B(B~=0)
also could help you:
C=max(A,B)

  0 Comments

Sign in to comment.

Sign in to answer this question.

Tags

Products