フィルターのクリア

Set vector elements of one vector to nonzero elements of another

2 ビュー (過去 30 日間)
CP
CP 2011 年 4 月 1 日
So I have two vectors:
v1, v2, both same size.
I want to find all the elements where v2 is not zero and set the corresponding elements in v1 to those values, while leaving the other elements in v1 untouched.
E.g.
v1=[1 2 3 4 5] v2=[1 0 1 1 0]
Code I need goes here
v1 --> [1 2 1 1 5]
Can I do this without loops? Thanks.
  1 件のコメント
Sean de Wolski
Sean de Wolski 2011 年 4 月 1 日
Another example of a well written question!

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

採用された回答

Sean de Wolski
Sean de Wolski 2011 年 4 月 1 日
v1(logical(v2)) = v2(logical(v2));
or on two lines:
idx = logical(v2);
v1(idx) = v2(idx);

その他の回答 (1 件)

CP
CP 2011 年 4 月 1 日
That gives a vector of the nonzero indices (e.g. [1 3 4] in the above example), but without looping through that resulting vector how can I set them to the values I need?
Edit: Ok the edited versions work. Thanks :)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by