Effacer les filtres
Effacer les filtres

How to randomly generate 0.1 or -0.1?

1 vue (au cours des 30 derniers jours)
Ricardo Gutierrez
Ricardo Gutierrez le 23 Avr 2018
Hello. Good day. I have this code:
for sm=0:0.1:0.1
f=sm*eye(N)
end
I get the following: f =
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
f =
0.1000 0 0 0 0 0 0 0 0 0
0 0.1000 0 0 0 0 0 0 0 0
0 0 0.1000 0 0 0 0 0 0 0
0 0 0 0.1000 0 0 0 0 0 0
0 0 0 0 0.1000 0 0 0 0 0
0 0 0 0 0 0.1000 0 0 0 0
0 0 0 0 0 0 0.1000 0 0 0
0 0 0 0 0 0 0 0.1000 0 0
0 0 0 0 0 0 0 0 0.1000 0
0 0 0 0 0 0 0 0 0 0.1000
I want to obtain the following: f =
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
f =
-0.1000 0 0 0 0 0 0 0 0 0
0 0.1000 0 0 0 0 0 0 0 0
0 0 -0.1000 0 0 0 0 0 0 0
0 0 0 -0.1000 0 0 0 0 0 0
0 0 0 0 0.1000 0 0 0 0 0
0 0 0 0 0 0.1000 0 0 0 0
0 0 0 0 0 0 0.1000 0 0 0
0 0 0 0 0 0 0 -0.1000 0 0
0 0 0 0 0 0 0 0 0.1000 0
0 0 0 0 0 0 0 0 0 -0.1000
As we can see, we generated 0.1 and -0.1 randomly. That's what I want randomly generated 0.1 and -0.1 I hope I have explained my question well. Greetings and thanks.

Réponse acceptée

Stephen23
Stephen23 le 23 Avr 2018
diag((2*randi(0:1,1,N)-1)/10)
  4 commentaires
Stephen23
Stephen23 le 23 Avr 2018

" Using this code that you did how to previously generate the matrix... and then the random matrix (0.1 or -0.1)"

It really works the other way around: first it generates a vector of random values, and then uses diag to form a matrix, placing those values along the diagonal. I am sure that you can read the randi and diag help to know what they do, and try the parts of the code yourself:

>> N = 6;
>> randi(0:1,1,N)
ans =
     1     0     1     0     0     0
>> (2*randi(0:1,1,N)-1)/10
ans =
          0.1          0.1         -0.1         -0.1         -0.1          0.1
>> diag((2*randi(0:1,1,N)-1)/10)
ans =
          0.1            0            0            0            0            0
            0          0.1            0            0            0            0
            0            0         -0.1            0            0            0
            0            0            0          0.1            0            0
            0            0            0            0          0.1            0
            0            0            0            0            0         -0.1
Ricardo Gutierrez
Ricardo Gutierrez le 23 Avr 2018
It is understood. Thank you very much

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by