How to randomly generate 0.1 or -0.1?

1 回表示 (過去 30 日間)
Ricardo Gutierrez
Ricardo Gutierrez 2018 年 4 月 23 日
コメント済み: Ricardo Gutierrez 2018 年 4 月 23 日
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.

採用された回答

Stephen23
Stephen23 2018 年 4 月 23 日
diag((2*randi(0:1,1,N)-1)/10)
  4 件のコメント
Stephen23
Stephen23 2018 年 4 月 23 日

" 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 2018 年 4 月 23 日
It is understood. Thank you very much

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by