From index list to logical index vector
47 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
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.
0 个评论
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
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
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 Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!