How to replace some values in an array with zero and some with values from another array?

23 ビュー (過去 30 日間)
A = [2 4 0 0 5 3 0 2 1 0 2];
B = [1 1 0 1];
I want to replace numbers in A greater than 0 with 0, and numbers in A which is 0 by the numbers in B in the order they are.
The new vector i want is C = [0 0 1 1 0 0 0 0 0 1 0];
I tried to use if statements inside a for loop:
for i = 1:length(A)
for j=1:length(B)
if A==0
C(i)=0;
else
C(i)=B(j);
end;
end;
end;
What happens is that j in B(j) is constant 4 (giving a value of B(4)=1 for all the B(j), and results in a C = [0 0 1 1 0 0 1 0 0 1 0])

採用された回答

madhan ravi
madhan ravi 2019 年 3 月 19 日
C=A;
C(A==0)=B;
C(A>0)=0

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2019 年 3 月 19 日
A = [2 4 0 0 5 3 0 2 1 0 2];
B = [1 1 0 1];
A1 = ~A;
C = double(A1);
C(A1) = B;

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by