필터 지우기
필터 지우기

writing a loop for differences of random numbers.

조회 수: 1 (최근 30일)
Jake
Jake 2014년 10월 24일
댓글: John D'Errico 2014년 10월 24일
hello, i needed to write a loop to create a vector of 1000 random numbers. then from there i needed to create a loop to subtract every random number, by ever other random number. basically generating a 1000x1000 vector. however i am lost at how to go about it. here is my code so far.
for i= 1:1000
b(i) =rand;
end
for i =1:1000,
c =b(i) - b(1:1000);
end

답변 (1개)

Mikhail
Mikhail 2014년 10월 24일
편집: Mikhail 2014년 10월 24일
%Generate: for i= 1:1000
b(i) =rand;
end
%Subtract:
c=zeros(1000,1000)
for i =1:1000
c(i,:)=b-b(i);
end
So in matrix c: c(i,j)=b(j)-b(i)
  댓글 수: 2
Mikhail
Mikhail 2014년 10월 24일
Also there is much faster way to generate those numbers, without for loop:
b=rand(1000,1);
John D'Errico
John D'Errico 2014년 10월 24일
Of course, IF you were to generate the numbers in a vectorized form, it would also be far more efficient to use bsxfun to do the entire computation in two lines.
b = rand(1000,1);
c = bsxfun(@minus,b,b');
This of course, is the power of MATLAB, that explicit loops are not needed for simple computations like this.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by