-1

I wanted to know how I can go about randomly placing numbers (up to 10 numbers) in a matrix. The numbers will range from 1 to 10.

I am starting with A = zeros(5,8), then randomly place the 10 random numbers around the matrix.

Example of matrix:

enter image description here

Joe
  • 357
  • 2
  • 10
  • 32
  • Anywhere between 0 to10 random numbers, or exactly 10? How are the random numbers distributed? – mikkola Mar 30 '16 at 16:30
  • 1
    `A = randi(10, [5 8])` ? – Amro Mar 30 '16 at 16:33
  • @Amro, thanks for your help!. the numbers are randomly distributed, and I wanted to replace exactly 10 zeros. This is just a sample test, as my matrix will be much larger (1024, N), where N is variable, and the number of non-zero entries will be 20. I am eventually trying to create a 20-Sparse matrix. Thanks. – Joe Mar 30 '16 at 16:37
  • @Joe use the `randperm` method, in that case `Idx = randperm(1024*N,20)` – Adriaan Mar 30 '16 at 16:38
  • @Adriaan, thanks for your input. When I use the command, `tmp = randperm(1:10*5)`, I get the error, `Size inputs must be scalar`. – Joe Mar 30 '16 at 16:40
  • 1
    `sprand`? your question is still not clear.. Edit and describe exactly what you're trying to do, an example would be nice – Amro Mar 30 '16 at 16:40

1 Answers1

3
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

Basically you use randperm to create a certain number of linear indices to index your matrix. Simply place the desired numbers there and you're done.

Community
  • 1
  • 1
Adriaan
  • 17,741
  • 7
  • 42
  • 75