# Hello, I need help with: Replace elements in Vector A with those of vector B of the same position, only if they meet a certain condition, otherwise replace by a zero. Thanks

2 ビュー (過去 30 日間)
MuluMe 2022 年 8 月 3 日
コメント済み: Jon 2022 年 8 月 3 日
I have Vectors A and B of the same length and a threshhold value:
Threshold = 4;
A = [3 7 1 3 10 3 4 1 5 5];
B = [5 3 6 1 6 3 5 4 9 4];
I want replace all values in A that are greater than threshold (A > Threshold) with values in B if they are less than the threshold (B < Threshold), otherwise make them zeros. In thi case, the new vector of A should be:
Thank you.
##### 1 件のコメント表示 なし非表示 なし
MuluMe 2022 年 8 月 3 日
Am so grateful team, for your brilliant ideas. They have worked.

サインインしてコメントする。

### 採用された回答

Jon 2022 年 8 月 3 日

I like @Torsten's one liner and use of the multiplication times the logical zeros to null out the values where B is greater than the threshold. Alternatively, you could do it like this in two lines and the logic is a little more obvious
Threshold = 4;
A = [3 7 1 3 10 3 4 1 5 5];
B = [5 3 6 1 6 3 5 4 9 4];
A(A>Threshold) = B(A>Threshold)
A = 1×10
3 3 1 3 6 3 4 1 9 4
A(A>Threshold) = 0 % in case any of the B's we put in are over the threshold set them to zero
A = 1×10
3 3 1 3 0 3 4 1 0 4
##### 3 件のコメント表示 2 件の古いコメント非表示 2 件の古いコメント
Jon 2022 年 8 月 3 日
Thanks for accepting my answer, but I think actually @Torsten approach looks the closest to what you describe. I think you can click on the accepted answer and change it if you want.

サインインしてコメントする。

### その他の回答 (2 件)

Torsten 2022 年 8 月 3 日

I kept the values in A unchanged that are less or equal to Threshold. If you also want to replace them by 0, take David's answer.
Threshold = 4;
A = [3 7 1 3 10 3 4 1 5 5];
B = [5 3 6 1 6 3 5 4 9 4];
A(A>Threshold) = B(A>Threshold).*(B(A>Threshold) < Threshold)
A = 1×10
3 3 1 3 0 3 4 1 0 0
##### 0 件のコメント表示 -1 件の古いコメント非表示 -1 件の古いコメント

サインインしてコメントする。

David Hill 2022 年 8 月 3 日
t=4;
A = [3 7 1 3 10 3 4 1 5 5];
B = [5 3 6 1 6 3 5 4 9 4];
idx=A>t&B<t;
A(idx)=B(idx);
A(~idx)=0
A = 1×10
0 3 0 0 0 0 0 0 0 0

サインインしてコメントする。

### カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

### Community Treasure Hunt

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

Start Hunting!

Translated by