2
votes

In Matlab, I would like to know how to assign values inside a matrix randomly for any given size matrix?

For example:

Enter non-zero elements in 3*3 matrix? 3

      1
      4
      7

These elements are to be randomly placed in 3*3 matrix and the remaining 6 elements become zero.

In general, for some number of non-zero elements we enter in a matrix, the remaining elements in the matrix become zero.

How do I write the code in Matlab for the above example? I have to give as input the number of non-zero elements and assign the input values randomly inside the matrix without specifying any particular row or column.

1
I would like to help edit this question to make it more clear for future viewers with similar problems, but I'm not sure what the sentance "No non-zero element we enter in a matrix remaining element in matrix becomes zero." means. Can you maybe describe it a bit more? Maybe show an example matrix? I am happy to help with English grammar.Cecilia
@2cents sorry it is number of non-zerosuser3789221
I edited the post to clarify the sentence. If you feel it doesn't represent what you were trying to say, feel free to roll back or let me know.Cecilia

1 Answers

5
votes

This is very simple to do using randperm and linear indexing

V = [1,4,7];
M = zeros(3);
M(randperm(numel(M), numel(V))) = V

If you have an old version of Matlab (see comments, this also applies if you're using Octave) then you can try:

V = [1,4,7];
M = zeros(3);
I = randperm(numel(M));
M(I(1:numel(V))) = V