Generating a random matrix which has zero entries as well

When I generate a random matrix (for example, with the following code)
bounds = [-15,10];
A = rand(m,m) * range(bounds) + bounds(1)
there is no zero entry in the matrix. Could you please tell me how can I create a random matrix which has zero entries as well?

7 Comments

What about a random matrix of integers?
A = randi([-15 15], m, m)
Approximately 1 in every 31 values will be zero.
Thank you so much for your answer. I need my matrix entries to be floatings numbers, not integers.
Well, then bear in mind that 0 is effectively 0.00000000 and is no more likely to emerge from the rand function than a number such as 1.23456789. That's why you are not seeing any zeros in the matrix.
Then the chances of getting exactly 0 are minuscule. There are roughly 2^64 values possible if you are using the double datatype (less, because there are some special cases). It is a bit too tricky to calculate from memory how many of those are in the range 0-1, but there are many of them.
You will either have to round, be extremely lucky, generate a giant array, or accept that there will not be any zeros in your matrix.
You are right. Understood. So to have zeros in my matrices, I either have to use the code
randi([-15 15], m, m)
to generate integer entries or to round entries in the matrix generated by the code
bounds = [-15,10];
A = rand(m,m) * range(bounds) + bounds(1)
Is it right?
There are several things you could do, but it depends on what properties you need your random distribution to have.
For example, you could generate the m*m random numbers as you originally did, but then generate a random number of zeros from 0:m*m, and fill them into random location in your array.
So, first, think carefully about what specific properties you need your random distribution to have, then we may be able to help you generate that distribution. It is not enough to say "numbers between -15 and 15, where some are zeros". You need to be very specific.
You are right. I sure will. Thank you very much for your exact eplanation.

Sign in to comment.

Answers (0)

Categories

Find more on Random Number Generation in Help Center and File Exchange

Asked:

on 5 Jun 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!