Nested for loop to generate random matrix
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
Voss
2021-11-8
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.
回答(1 个)
John D'Errico
2021-11-8
编辑:John D'Errico
2021-11-8
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Genetic Algorithm 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!