-2

Suppose an index vector in binary like below

Input

1 1 0 0 1 0 1

1 2 3 4 5 6 7

Intended output

1 2 5 7

which denotes nth number to be chosen. So I want to change 1 1 0 0 1 0 1 to 1 2 5 7, is there some easy way for this?

hhh
  • 50,788
  • 62
  • 179
  • 282
  • I have earlier done `vals=1:length(dataStructure); vals(indicesBinary)` but looking for a more elegant solution. – hhh Nov 30 '13 at 13:02

2 Answers2

2

If you actually want to use your output to index another vector, do it directly.

You just need to transform your binary vector to logical

A = [1 1 0 0 1 0 1];    %assuming its double
B = [1 2 3 4 5 6 7];

C = B( logical(A) )

C =

     1     2     5     7
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
1

The solution is using the function find(indicesBinary)

kamjagin
  • 3,614
  • 1
  • 22
  • 24
  • Ofc, why I keep forgetting this...+1. – hhh Nov 30 '13 at 13:04
  • 2
    :). Just remember that if you want to use it for indexing another vector, using find as an intermediate step is actually slower than using the indicesBinary directly – kamjagin Nov 30 '13 at 13:05
  • You mean it is better to do `vals=1:length(dataStructure); vals(logical(indicesBinary))`? – hhh Nov 30 '13 at 13:06
  • Not at all. Find is more efficient if you want to do this. But if you want to use vals or indiciesBinary to select values from a different vector, using indiciesBinary directly will be faster. – kamjagin Nov 30 '13 at 13:07
  • so `actualVals = dataStructure(indicesBinary);` gives the same result but is faster than `actualVals = dataStructure(find(indicesBinary));`. So if index positions is what you want, use `find`. If you actually want to index, use indicesBinary directly (but cast them to logical if they aren't already) – kamjagin Nov 30 '13 at 13:09
  • Now I cannot understand `"if you want to do this"`: which version is faster or does it depend? – hhh Nov 30 '13 at 14:07
  • 2
    So let's say you have some vector `v = [13,63,34,1];` and you have a binary index vector `b_idx = [0, 1, 1, 0];` If you want to index v with b_idx, you do `sel_v = v(b_idx);`. The output is sel_v = [63,34] and is fast+. If you instead want to know the indexes that b_idx correspond to (as posed in the question), you do `idx = find(b_idx);`. The output is idx = [2,3]. You can then off course also do `sel_v = v(idx);` to get sel_v = [63,34]. Doing `find` and then indexing with `idx` to get [63,34] is also fast, but not as fast as using `b_idx` directly. Hope that clears things up – kamjagin Nov 30 '13 at 14:15