Matlab 在矩阵的每行仅生成一个非零元素
我想构造一个矩阵,其中我们不仅在每一行有一个“1”,而且在一个随机的位置也有一个“。e、 gMatlab 在矩阵的每行仅生成一个非零元素,matlab,Matlab,我想构造一个矩阵,其中我们不仅在每一行有一个“1”,而且在一个随机的位置也有一个“。e、 g 我希望矩阵的大小为大小m乘以n。这项任务似乎很简单,但我不确定该怎么做。谢谢。这将得到每列中要放入的1的数量,因为它只有1,我们被授权在转置后,新矩阵每行中只有一个1 参数是生成的矩阵中的行数和列数 function [M] = getMat(n,d) M = zeros(d,n); sz = size(M); nnzs = 1; inds = []; for
我希望矩阵的大小为大小
m乘以n
。这项任务似乎很简单,但我不确定该怎么做。谢谢。这将得到每列中要放入的1的数量,因为它只有1,我们被授权在转置后,新矩阵每行中只有一个1
参数是生成的矩阵中的行数和列数
function [M] = getMat(n,d)
M = zeros(d,n);
sz = size(M);
nnzs = 1;
inds = [];
for i=1:n
ind = randperm(d,nnzs);
inds = [inds ind.'];
end
points = (1:n);
nnzInds = [];
for i=1:nnzs
nnzInd = sub2ind(sz, inds(i,:), points);
nnzInds = [nnzInds ; nnzInd];
end
M(nnzInds) = 1;
M = M.';
end
例如:
getMat(5, 3)
ans =
0 0 1
1 0 0
0 1 0
1 0 0
0 0 1
我建议采取以下办法:
N = 3; M = 6; %defines input size
mat = zeros(M,N); %generates empty matrix of NxN
randCols = randi([1,N],[M,1]); %choose columns randomally
mat(sub2ind([M,N],[1:M]',randCols)) = 1; %update matrix
% generate a random integer matrix of size m by n
m = randi(5,[5 3]);
% find the indices with the maximum number in a row
[Y,I] = max(m, [], 2);
% create a zero matrix of size m by n
B = zeros(size(m));
% get the max indices per row and assign 1
B(sub2ind(size(m), 1:length(I), I')) = 1;
结果
mat =
0 0 1
1 0 0
0 0 1
0 0 1
0 1 0
0 1 0
考虑这种方法:
N = 3; M = 6; %defines input size
mat = zeros(M,N); %generates empty matrix of NxN
randCols = randi([1,N],[M,1]); %choose columns randomally
mat(sub2ind([M,N],[1:M]',randCols)) = 1; %update matrix
% generate a random integer matrix of size m by n
m = randi(5,[5 3]);
% find the indices with the maximum number in a row
[Y,I] = max(m, [], 2);
% create a zero matrix of size m by n
B = zeros(size(m));
% get the max indices per row and assign 1
B(sub2ind(size(m), 1:length(I), I')) = 1;
结果:
B =
0 1 0
0 0 1
1 0 0
0 1 0
1 0 0
参考: