From index list to logical index vector
49 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (2)
Haris K.
le 16 Fév 2021
Modifié(e) : Haris K.
le 16 Fév 2021
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 commentaires
Star Strider
le 20 Août 2015
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 commentaires
Star Strider
le 21 Août 2015
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
le 1 Avr 2022
Modifié(e) : Rich Gerbino
le 1 Avr 2022
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);
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!