Filter löschen
Filter löschen

writing a loop for differences of random numbers.

1 Ansicht (letzte 30 Tage)
Jake am 24 Okt. 2014
Kommentiert: John D'Errico am 24 Okt. 2014
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;
for i =1:1000,
c =b(i) - b(1:1000);

Antworten (1)

Mikhail am 24 Okt. 2014
Bearbeitet: Mikhail am 24 Okt. 2014
%Generate: for i= 1:1000
b(i) =rand;
for i =1:1000
So in matrix c: c(i,j)=b(j)-b(i)
  2 Kommentare
Mikhail am 24 Okt. 2014
Also there is much faster way to generate those numbers, without for loop:
John D'Errico
John D'Errico am 24 Okt. 2014
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.

Melden Sie sich an, um zu kommentieren.


Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange


Community Treasure Hunt

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

Start Hunting!

Translated by