From index list to logical index vector

조회 수: 75 (최근 30일)
Massimiliano Salsi
Massimiliano Salsi 2015년 8월 20일
편집: Rich Gerbino 2022년 4월 1일
Hello, If I have a specific list of indexes, I can acces a subset of the element of a vector:
N=10;
a = rand(2*N,1);
period = 7;
list = 1:period:N;
a(list)
In my code I want that subset to be addressed with logical indexing (for various reasons). How do I convert that list to logical indexing?
The only solution I can think of requires building the list of all the indexes:
all_idx = (1:length(a));
logical_idx = ismember(all_idx, list);
a(logical_idx)
Is there shorter more readable way of doing this? Please do not answer:
a(ismember(1:length(a),list)) % ;-)
Thanks

답변 (2개)

Haris K.
Haris K. 2021년 2월 16일
편집: Haris K. 2021년 2월 16일
I changed the variable names for brevity.
function lgc = unfind(idx, N)
%Go from indicies into logical (for vectors only)
lgc = false(N,1);
lgc(idx) = true;
end
And you can check it:
X = [10 20 15 16 19];
N = length(X);
idx = find(X>=19);
lgc = unfind(idx, N);
X(lgc)
X(idx)
The two last rows are equivalent.

Star Strider
Star Strider 2015년 8월 20일
See if this does what you want:
N=10;
a = rand(2*N,1);
period = 7;
list = 1:period:N;
logical_idx(list) = logical(1)
a(logical_idx)
logical_idx =
1 0 0 0 0 0 0 1
ans =
0.52399
0.16543
  댓글 수: 3
Star Strider
Star Strider 2015년 8월 21일
My pleasure.
It’s also an efficient, one-line solution.
Using true is the same as using logical(1).
It would be easier to use sum or nnz to count the 1 values, then subtract that from length(a) to get the number of zeros.
Rich Gerbino
Rich Gerbino 2022년 4월 1일
편집: Rich Gerbino 2022년 4월 1일
Thanks, exactly what I was looking for. If you want to preserve the original vector length (in my case I also want to use ~logical_idx), you can modify the above code slightly with:
logical_idx = false(2*N,1);
logical_idx(list) = logical(1);

댓글을 달려면 로그인하십시오.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by