I have an index vector that I have to change and I want to change the values of them

19 ビュー (過去 30 日間)
Dani Tormo
Dani Tormo 2013 年 2 月 18 日
編集済み: Dani Tormo 2013 年 11 月 13 日
Hi all!
I have a vector:
v = [1 0 0 1 1]
I got another index vector that says me which of these values have to be changed to 1:
index = [1 5 3]
The result should be:
v = [1 0 1 0 1]
The code to do this with a for is this one:
for i=1:Nc_needed
v(index(i)) = 1;
end
I know that there are ways to do it in only one line. Anyone knows how?

採用された回答

Wayne King
Wayne King 2013 年 2 月 18 日
編集済み: Wayne King 2013 年 2 月 18 日
v = [1 0 0 1 1];
idx = [1 5 3];
v(idx) = 1;
But that does not give exactly what you said originally because orignally, elements 1,4,and 5 were already ones, so all the above does is set element 3 to a 1.
Another way
v = zeros(1,5);
v(idx) = 1;
So the way to do it with one line is create a vector of indices that you want to change -- the indices must be greater than or equal to 1 and less than or equal to the length of the vector, then use that vector to assign the value to "data" vector
  1 件のコメント
Dani Tormo
Dani Tormo 2013 年 2 月 18 日
What a quick response! The second is what I was looking for.
Many thanks!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by