3

if i have an initial array A of twenty numbers in the order 1 to 20,

 A = [1,2,3,4,5,...,20]

and have another random array B:

  B = [1, 15, 3, 20, 7]

and want to output a column vector C of the form

  C = [1 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1]

Note that C has a 1 at the indices at which B has a value.

I have tried the following:

n=20;
C = zeros(n, 1);
for i=1:length(B)
   C(B(i))=1;
end
1
  • 1
    What A has got to do with anything? Commented Jun 12, 2012 at 7:03

3 Answers 3

2

in a one-liner:

full(sparse(B,1,1,max(B),1))

and you could also drop the full function, most matlab matrix operation can deal with sparse matrices. But of course it depends on what you actually want to do.

Sign up to request clarification or add additional context in comments.

Comments

2

Another one-liner:

C = accumarray(B(:), 1, [], @(x)1)

3 Comments

Wrap it in logical() in case there are non-unique values in B.
@Simon: good catch, thank you. I solved it a slightly different way (to keep the result of type double).
+1: accumarray is actually specifically made just for these kind of things, why didn't I think of that :p
1

Here is a vectorized solution:

Firstly, initialize C

   C = zeros( max(B),1);

Then use array indexing:

   C(B) = 1;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.