Nested for loop to generate random matrix

11 views (last 30 days)
Jessica Peterson
Jessica Peterson on 8 Nov 2021
Commented: Voss on 8 Nov 2021
Hello all,
I need to used a for loop to genetate a random matrix using the rand function. Thus far, I have the following:
for i = 1:500;%Generates random angle for each particle step
for j =1:50
theta(i,j) = 360*rand; %Generates random angle
end
end
This gives me a matrix of the appropriate size, but only the first row and first column contain randomly generated numbers. How do I use a for loop to generate all of the cells in the 50x500 matrix?
  1 Comment
Voss
Voss on 8 Nov 2021
What do the 2nd and subsequent rows and columns of theta contain, if they do not contain random numbers? When I run this code, I get a theta that is full of random values.
BTW, you can avoid the loops and just say
theta = 360*rand(500,50);
to do the same thing.

Sign in to comment.

Answers (1)

John D'Errico
John D'Errico on 8 Nov 2021
Edited: John D'Errico on 8 Nov 2021
No. That simply is not true, that only the first row and column are random.
for i = 1:10; %Generates random angle for each particle step
for j =1:5
theta(i,j) = 360*rand; %Generates random angle
end
end
theta
theta = 10×5
273.2896 50.0424 343.0915 316.6937 309.6810 6.6930 102.6195 340.3112 67.6372 8.7269 235.8056 207.2556 98.8641 118.1681 357.4238 321.4272 180.5290 339.3406 213.2750 291.8362 264.8494 109.1814 302.3746 317.8165 141.4980 190.9146 191.2471 303.8525 319.8667 211.3416 319.4951 14.7676 50.2789 95.7806 143.1623 11.9558 47.5494 63.4894 247.6178 68.2954 288.0799 228.6950 212.0602 239.7204 36.2135 109.3971 86.1331 221.1050 323.5354 121.5858
Totally random. No matter what you actually did, the code you have written here does produce a matrix with independent random elements. Is it the most efficient code? Ye gods no! But it does work.

Community Treasure Hunt

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

Start Hunting!

Translated by