0

I want to create a 3D matrix of dimensions 681x711x29 with values between -0.3 and 0.3.

W=randi([-0.3, 0.3],681,711,29);

It gives the error:

First input must be a positive scalar integer value IMAX, or two integer values [IMIN IMAX] with IMIN less than or equal to IMAX.

I think it doesn't work because they're decimal numbers. How do I make a 3D matrix with random decimal numbers between -0.3 and 0.3?

Jellyse
  • 839
  • 7
  • 22
  • Check the `randi` function. It returns random **integers** so it's not appropriate for what you need. – alpereira7 Dec 04 '18 at 12:50
  • `rand` should be better. Try W = rand(681,711,29)*(0.3 - (-0.3)) - 0.3; – alpereira7 Dec 04 '18 at 12:57
  • specify better what you want: real numbers between -0.3 and 0.3, or rational numbers with a fixed number of decimal places? What is a "decimal number" for you? – Stefano M Dec 04 '18 at 13:00
  • 2
    Possible duplicate of [Generate a random number in a certain range in MATLAB](https://stackoverflow.com/questions/5077800/generate-a-random-number-in-a-certain-range-in-matlab) – Wolfie Dec 04 '18 at 14:02
  • Are you wanting numbers *uniformly distributed* on the interval [-0.3, 0.3]? If so, [this answer](https://stackoverflow.com/a/53613584/8239061) is good. If not, please specify how you'd like the numbers distributed on that interval. – SecretAgentMan Dec 04 '18 at 14:55

1 Answers1

4

First off, you need the rand function and not the randi function. rand will return a matrix with random numbers between 0 and 1. You can then transform it to the [-0.3 0.3] interval using the following formula.

W = -0.3 + (0.3-(-0.3))*rand(681,711,29);

or generally for an interval [a, b]

W = a + (b-a)*rand(m,n,...);
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120