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?
Create random integers between -3 and 2, but replace the zeros with 3s:
x = randi([-3,2],4);x(x==0)=3
@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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With