Generating random 3D vectors
23 次查看(过去 30 天)
显示 更早的评论
Hi, I'm trying to create 100 random 3D vectors with entries [-1,1]. I'm new to matlab so it's very confusing to me at the moment.
I would very much appreciate your help.
Thank you.
0 个评论
回答(3 个)
John D'Errico
2016-10-28
编辑:John D'Errico
2016-10-28
rand(100,3)*2-1
Read the help. It shows how to do exactly this type of thing.
doc rand
I'm not sure why you are confused though. Rand generates random numbers between 0 and 1. Multiply by 2, and they are between 0 and 2. Subtract 1, and what do you have?
The above assume that you intended elements that lie in the interval [-1,1]. That is what that notation shows of course. If you really intended only the integer elements -1 and 1 as possibilities, then you should say so clearly. But that too is easy, and is a trivial extension of the above.
round(rand(100,3))*2-1
Then you want to generate 100 sets of 3 such numbers. A vector is just a list of three numbers. 100 of them is an array, so store them in a100x3 array.
0 个评论
James Tursa
2016-10-28
编辑:James Tursa
2016-10-28
E.g., see this discussion:
If you mean a 3-element vector (i.e., a vector in 3-space), then just:
v = 2*round(rand(3,100))-1; % for values from the discrete integer set -1,+1
or
v = 2*rand(3,100)-1; % for floating point values between -1 to +1
If you mean 3-element vectors with endpoints uniformly distributed on a unit sphere, then you would need to do something else. E.g. using the randn function:
v = randn(3,100);
v = bsxfun(@rdivide,v,sqrt(sum(v.*v)));
0 个评论
Charles Jing
2022-3-5
I guess is Jason asking for this?
x=rand(100,100,100)*2-1;
2 个评论
John D'Errico
2022-3-5
Surely not so. That generates an array of size 100x100x100. They are not sets of random numbers in a 3-dimensional space, but a 3-dimensional array of numbers. Had you said
x = rand(100,3)*2-1;
or
x = rand(3,100)*2-1;
then your answer would have been correct. In these two cases, you can now view the rows (or columns as appropriate) as sets of random numbers in a 3-dimensional space, so R^3.
Remember, the request was to generate 100 random 3-d vectors.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Random Number Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!