How to create a matrix with random integer elements between -3 and 3, but not 0 in MATLAB

To create a random matrix, I used the following:

x = randi ([- 3,3], 4)

However, I do not need zeros in my output matrix. How can i do this?

+5
source share
4 answers

Create random integers from -3 to 2, but replace zeros with 3s:

x = randi([-3,2],4);x(x==0)=3 
+8
source

@David provides a neat solution for your specific problem. But the following solution will work for any set of numbers (note that they do not have to be integers), although I configured it for your specific problem.

 OutputSize = [20, 1]; %Size of output matrix A = [-3; -2; -1; 1; 2; 3]; %Vector of numbers you want to sample from (can be whatever you want) x = A(randi(length(A), OutputSize)); %We randomly select the indices of A 

You might want to enable the above functions with inputs A and OutputDim .

You can even reuse cell array elements with this method ...

EDIT: Corrected code allowing outputting an array of any size as suggested by @Divakar in the comments

+7
source

You can use an iterative approach to check for zeros and replace them with a smaller set of randomized elements within the same interval [-3,3] . We continue to do this until there are no zeros left.

The code to achieve this approach would be something like this:

 N = 4; %// datasize x1 = randi([-3,3],N); %// the first set/iteration of random numbers done = false; %// flag to detect if any zeros are left after iterative substitution while ~done %// keep the loop running until no zeros are found x1((x1==0)) = randi([-3,3],numel(find(x1==0)),1); %// substitute zeros with %// smaller set of random numbers done = all(x1(:)~=0); end 
+4
source

This may not be the fastest solution, but there is a randsample function in the statistics toolbar that does just that:

 m = 4; %// number of rows n = 4; %// number of columns values = [-3:-1, 1:3]; %// values to sample from x = reshape(randsample(values, m*n, true), [mn]); 
+2
source

Source: https://habr.com/ru/post/1205924/


All Articles