From index list to logical index vector
48 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
Haris K.
el 16 de Feb. de 2021
Editada: Haris K.
el 16 de Feb. de 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 comentarios
Star Strider
el 20 de Ag. de 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 comentarios
Star Strider
el 21 de Ag. de 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
el 1 de Abr. de 2022
Editada: Rich Gerbino
el 1 de Abr. de 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);
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!