Matlab converts a vector to a binary matrix

I have a vector v of size (m, 1) whose elements are integers selected from 1: n. I want to create a matrix M of size (m, n) whose elements M (i, j) are equal to 1 if v (i) = j, otherwise they are equal to zero. I do not want to use loops and would like to implement this as a simple vector matrix manipulation.

So, I first thought to create a matrix with repeating elements

 M = v * ones(1,n) % this is a (m,n) matrix of repeated v

For example, v = [1,1,3,2] 'm = 4 and n = 3

M =
     1     1     1
     1     1     1
     3     3     3
     2     2     2

then I need to create a comparison vector c of size (1, n)

c = 1:n
1 2 3

Then I need to do a series of logical comparisons

M(1,:)==c % this results in [1,0,0]
.
M(4,:)==c % this results in [0,1,0]

However, I thought it should be possible to follow the last steps on each individual line in a compact matrix notation, but I'm at a dead end and not well aware of indexing. The end result should be

M =
     1     0     0
     1     0     0
     0     0     1
     0     1     0
+4
3

bsxfun :

>> n = 3;
>> v = [1,1,3,2].';
>> M = bsxfun(@eq, v, 1:n)

M =

     1     0     0
     1     0     0
     0     0     1
     0     1     0

, . bsxfun - , B inary S ingleton E X. , / , . , , . v - , , - , . - 1 n. , - v / , n, , v. eq/ . 1s , 2s , n. eq , , v .


. , n=max(v), Luis . timeit :

function timing_binary

n = 10000;
v = randi(1000,n,1);
m = numel(v);

    function luis_func()
    M1 = full(sparse(1:m,v,1));       
    end

    function luis_func2()
    %m = numel(v);
    %n = 3; %// or compute n automatically as n = max(v);
    M2 = zeros(m, n);
    M2((1:m).' + (v-1)*m) = 1;      
    end

    function ray_func()
    M3 = bsxfun(@eq, v, 1:n);
    end

    function op_func()
    M4= ones(1,m)'*[1:n] == v * ones(1,n);
    end

t1 = timeit(@luis_func);
t2 = timeit(@luis_func2);
t3 = timeit(@ray_func);
t4 = timeit(@op_func);

fprintf('Luis Mendo - Sparse: %f\n', t1);
fprintf('Luis Mendo - Indexing: %f\n', t2);
fprintf('rayryeng - bsxfun: %f\n', t3);
fprintf('OP: %f\n', t4);


end

n = 10000, v - 10000 x 1 1 1000. , , , .

, :

>> timing_binary
Luis Mendo - Sparse: 0.015086
Luis Mendo - Indexing: 0.327993
rayryeng - bsxfun: 0.040672
OP: 0.841827

Luis Mendo sparse ( ), bsxfun, , . .

+5

, n max(v), sparse:

v = [1,1,3,2];
M = full(sparse(1:numel(v),v,1));

sparse , , - , - . full.


- , , :

v = [1,1,3,2];
m = numel(v);
n = 3; %// or compute n automatically as n = max(v);
M = zeros(m, n);
M((1:m) + (v-1)*m) = 1;
+3

, , , - , . , ,

M= ones(1,m)'*[1:n] == v * ones(1,n)
+1

Source: https://habr.com/ru/post/1606635/


All Articles