Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binary array in MATLAB

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
like image 970
nyxee Avatar asked May 13 '26 02:05

nyxee


2 Answers

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.

like image 194
Gunther Struyf Avatar answered May 15 '26 15:05

Gunther Struyf


Another one-liner:

C = accumarray(B(:), 1, [], @(x)1)
like image 25
Amro Avatar answered May 15 '26 14:05

Amro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!