Azzera filtri
Azzera filtri

How to randomly generate 0.1 or -0.1?

1 visualizzazione (ultimi 30 giorni)
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.

Risposta accettata

Stephen23
Stephen23 il 23 Apr 2018
diag((2*randi(0:1,1,N)-1)/10)
  4 Commenti
Stephen23
Stephen23 il 23 Apr 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 il 23 Apr 2018
It is understood. Thank you very much

Accedi per commentare.

Più risposte (0)

Categorie

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

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by