Nested for loop to generate random matrix
조회 수: 5 (최근 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에서 Random Number Generation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!