0

Or more generally, a list of integers from 1 to n into an n-dimensional vector of zeros and ones?

Charles
  • 50,943
  • 13
  • 104
  • 142
John Lawrence Aspden
  • 17,124
  • 11
  • 67
  • 110

1 Answers1

3
A = [ 1, 2, 4, 8];
B = false( 1,A(end) );
B(A) = true;

returns:

B =

     1     1     0     1     0     0     0     1

and optional: B = double(B) if you need it as doubles.

or:

B = zeros( 1,A(end) );
B(A) = 1;

however.

Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
  • why are you initializing `B` with `numel (A)`? In the example given, you would initialize a 1x4 vector which is not what was asked. Simply `B(A) = true` or `B(A) = 1` is enough. – carandraug Dec 08 '13 at 19:02
  • @carandraug: `numel(A)` is nonsense, thats right. But I'd keep the initialization, to make sure all other values are `0`/`false` – Robert Seifert Dec 08 '13 at 21:02
  • all other values are false or zero by default, you don't have to worry about it. If you really want to initialize `B`, which I still think you don't have to (the assigning values to other indices **is** the initialization), use `max (A(:))`. Initializing to the wrong place will actually be worse since the assignment will force a resize. – carandraug Dec 09 '13 at 06:50
  • @carandraug I disagree. If you e.g. have a variable `B = 01010101` in your workspace and assign `B(A)=true` it won't be the desired result. If you clear all before, of course you need it. But during the development process I'd keep this line. – Robert Seifert Dec 09 '13 at 07:16