Azzera filtri
Azzera filtri

Obtaining all zeros from rand

1 visualizzazione (ultimi 30 giorni)
Damiano Capocci
Damiano Capocci il 30 Set 2017
Modificato: Stephen23 il 1 Ott 2017
Hi, i'm working with rand but when i do x(1,9)=rand the vector x has the first eight components are always equal to zero, in particular if i do x(1,3)=rand the first and the second are zero. I've also noticed that if the code is :
for n = drange(1:45)
x(1,n)=rand
end
it creates a correct vector of random numbers on the contrary (like the previous one) :
clear all;
x(1,45)=rand
it gives only the 45th component different from zero.
How can i fix it ?
  2 Commenti
Damiano Capocci
Damiano Capocci il 30 Set 2017
Modificato: Damiano Capocci il 30 Set 2017
yes thnx, it works but i would like to know why it happens that situation.
Stephen23
Stephen23 il 30 Set 2017
Modificato: Stephen23 il 1 Ott 2017
@Damiano Capocci: this has really nothing to do with rand, and is entirely due to your indexing during the allocation:
x(1,45) = ...
If x does not exist when that lines is run, then MATLAB creates x. Your indexing specifies just one element of that array (1st row, 45th column), and so MATLAB puts whatever value happens to be on the right-hand-side of the allocation into that location. Your indexing does not refer to the other elements of the first row (from 1 to 44) and so MATLAB simply fills them in with a default value (zero).
Note that using a loop to fill an array like this is not efficient or recommended:
for n = drange(1:45)
x(1,n)=rand
end
Much simpler is to call rand and specify the size array that you need:
x = rand(1,45)

Accedi per commentare.

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 30 Set 2017
Modificato: Andrei Bobrov il 30 Set 2017
x = rand(1,45)

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by