Filter löschen
Filter löschen

How to randomly generate 0.1 or -0.1?

3 Ansichten (letzte 30 Tage)
Ricardo Gutierrez
Ricardo Gutierrez am 23 Apr. 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.

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by