Convert integer to logical array in MATLAB

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

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     1     0     0     0     0     0     0     0     0 

Now, I want to vectorize this process for each row. Writing repmat(1:10, 2, 1) == [2 5]' I expect to get

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

But instead, this error occurs:

Error using ==
Matrix dimensions must agree.

Can I vectorize this process, or is a for loop the only option?

回答1:

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.



回答2:

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 


回答3:

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; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!