Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

To generate a random matrix, I have used the following:

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

However I don't want any zeros in my output matrix. How can I do this?

like image 253
newzad Avatar asked Oct 31 '14 05:10

newzad


3 Answers

Create random integers between -3 and 2, but replace the zeros with 3s:

x = randi([-3,2],4);x(x==0)=3
like image 188
David Avatar answered Nov 01 '22 11:11

David


@David provides a neat solution for your specific problem. But the following solution will work for any set of numbers (note, they don't need to be integers), although I've set it up 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 turn the above into a function with inputs A and OutputDim.

You could even re-sample elements of a cell array using this method...

EDIT: Adjusted the code to allow output array of any size following the suggestion of @Divakar in the comments

like image 24
Colin T Bowers Avatar answered Nov 01 '22 09:11

Colin T Bowers


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

The code to achieve such an 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
like image 29
Divakar Avatar answered Nov 01 '22 10:11

Divakar