How to swap array element from two arrays conditionally

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

 채택된 답변

Akira Agata
Akira Agata 2019년 12월 4일
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

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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

태그

질문:

2019년 12월 4일

댓글:

2019년 12월 4일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by