How to choose all other indices than ones I know?

조회 수: 2 (최근 30일)
Markus Toivonen
Markus Toivonen 2018년 3월 7일
답변: Jan 2018년 3월 7일
Hello.
If have an array
a = [11 12 13 14 15]
and I know that I want to change every other indice to NaN apart from indices 2 and 3. How do I do this?
I tried
a(~[2,3]) = NaN;
but it does not do anything. Thanks!

채택된 답변

Birdman
Birdman 2018년 3월 7일
a(setdiff(1:numel(a),2:3))=NaN

추가 답변 (2개)

Jos (10584)
Jos (10584) 2018년 3월 7일
Here are two options
a = [11 12 13 14 15]
i = [2 3]
b1 = nan(size(a))
b1(i) = a(i)
b2 = a
i2 = setdiff(1:numel(a),i)
b2(i2) = nan

Jan
Jan 2018년 3월 7일
While setdiff is the nicer solution, it has a remarkable overhead. Logical indexing is usually faster:
a = 1:10;
index = true(size(a));
index([2,3]) = false;
a(index) = NaN;

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by