Nested for loop to generate random matrix
2 views (last 30 days)
Show older comments
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
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.
Answers (1)
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
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.
0 Comments
See Also
Categories
Find more on Genetic Algorithm in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!