最有效的生成方式是什么
>> A
A =
0 1 1
1 1 0
1 0 1
0 0 0
与
>> B = [2 3; 1 2; 1 3]
B =
2 3
1 2
1 3
在 MATLAB 中?
例如,B(1, :)
,即[2 3]
,表示A(2, 1)
和A(3, 1)
为true
。
我的尝试仍然需要一个 for 循环,迭代 B
的行。是否有无循环或更有效的方法来执行此操作?
最佳答案
不过,这只是多种方式中的一种 sub2ind
是专门用于此目的的函数:
%// given row indices
B = [2 3; 1 2; 1 3]
%// size of row index matrix
[n,m] = size(B)
%// size of output matrix
[N,M] = deal( max(B(:)), n)
%// preallocation of output matrix
A = zeros(N,M)
%// get col indices to given row indices
cols = bsxfun(@times, ones(n,m),(1:n).')
%// set values
A( sub2ind([N,M],B,cols) ) = 1
A =
0 1 1
1 1 0
1 0 1
如果你想要一个逻辑矩阵,请将以下内容更改为行
A = false(N,M)
A( sub2ind([N,M],B,cols) ) = true
替代解决方案
%// given row indices
B = [2 3; 1 2; 1 3];
%// number if rows
r = 4; %// e.g. = max(B(:))
%// number if cols
c = 3; %// size(B,1)
%// preallocation of output matrix
A = zeros(r,c);
%// set values
A( bsxfun(@plus, B.', 0:r:(r*(c-1))) ) = 1;
关于matlab - 通过给定的真值行索引生成逻辑矩阵的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38410437/