From index list to logical index vector

48 visualizzazioni (ultimi 30 giorni)
Massimiliano Salsi
Massimiliano Salsi il 20 Ago 2015
Modificato: Rich Gerbino il 1 Apr 2022
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

Risposte (2)

Haris K.
Haris K. il 16 Feb 2021
Modificato: Haris K. il 16 Feb 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.

Star Strider
Star Strider il 20 Ago 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 Commenti
Star Strider
Star Strider il 21 Ago 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
Rich Gerbino il 1 Apr 2022
Modificato: Rich Gerbino il 1 Apr 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);

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by