Convert integer to logical array in MATLAB

后端 未结 3 1515
滥情空心
滥情空心 2021-01-21 04:21

I want to convert an integer i to a logical vector with an i-th non-zero element. That can de done with 1:10 == 2, which returns

0              


        
相关标签:
3条回答
  • 2021-01-21 04:29

    You can use bsxfun:

    >> bsxfun(@eq, 1:10, [2 5].')
    ans =
    
       0   1   0   0   0   0   0   0   0   0
       0   0   0   0   1   0   0   0   0   0
    

    Note the transpose .' on the second vector; it's important.

    0 讨论(0)
  • 2021-01-21 04:29

    Another way is to use eye and create a logical matrix that is n x n long, then use the indices to index into the rows of this matrix:

    n = 10;
    ind = [2 5];
    
    E = eye(n,n) == 1;
    out = E(ind, :);
    

    We get:

    >> out
    
    out =
    
         0     1     0     0     0     0     0     0     0     0
         0     0     0     0     1     0     0     0     0     0
    
    0 讨论(0)
  • 2021-01-21 04:48

    Just another possibility using indexing:

    n = 10;
    ind = [2 5];
    x=zeros(numel(ind),n);
    x(sub2ind([numel(ind),n],1:numel(ind),ind))=1;
    
    0 讨论(0)
提交回复
热议问题