1

Suppose I have an array a of bounded integers (in this case bounded by 5):

a = [3 4 4 2 1 5 5];

I want to convert this array of integers to a length(a) x 5 matrix A where each row is a bit array with a 1 in the column indexed by the integer from a:

A = [0 0 1 0 0;
     0 0 0 1 0;
     0 0 0 1 0;
     0 1 0 0 0;
     1 0 0 0 0;
     0 0 0 0 1;
     0 0 0 0 1];

This is easily accomplished with a for loop:

n = length(a)
A = zeros(n, max(a(:)));
for k = 1 : n
  A(k, a(k)) = 1;
end

I am looking for a vectorized implementation that does not use a for loop.

1 Answer 1

2

Two possible methods:

  1. use sparse:

    A = sparse( 1:n, a, 1, n, max(a(:)) );  
    

    if you want a non-sparse result

    full(A);
    
  2. Using sun2ind:

    A = zeros( n, max(a(:)) );
    A( sub2ind(size(A), 1:n, a ) ) = 1;
    
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the quick response and multiple solutions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.