How to randomly generate 0.1 or -0.1?

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by