将数字随机添加到 N x M 零矩阵

Randomly add numbers to a N x M zero matrix

我想知道如何在矩阵中随机放置数字(最多 10 个数字)。数字范围从 1 到 10。

我从 A = zeros(5,8) 开始,然后将 10 个随机数随机放置在矩阵周围。

矩阵示例:

N=20;                            %// number of columns
M=1024;                          %// number of rows
NumRand = 20;                    %// number of random numbers
RandomScalars = rand(NumRand,1); %// random numbers
MyMatrix= sparse(M,N);           %// initialise matrix   
Idx = randperm(M*N,NumRand);     %// get indices to be filled
MyMatrix(Idx) = RandomScalars;   %// fill indexed places

基本上你使用 randperm to create a certain number of linear indices 来索引你的矩阵。只需将所需的数字放在那里即可。