Create a matrix with rand
3 次查看(过去 30 天)
显示 更早的评论
I have a
vector = 2*rand(1,3)-1
I want to create a matrix with x lines and columns the vectors.
I have done the following:
x=10;
for i=1:x
2*rand(1,3)-1
end
But I want to write the loop in another way,in a one line because i want to use that matrix. I tried this:
a=2*rand(1,3)(size(1:x)); % but i can't figure how.
Also, is there a way not to write 2*rand(1,3)-1 all the time?Because, if i write "vector" ,it will keep only one value,it doesn't generate random numbers.
1 个评论
Todd Flanagan
2011-1-20
George, I moved your reply to a comment in Doug's answer. You may want to accept Doug's answer if it helped you.
回答(1 个)
Doug Hull
2011-1-20
You will want to create a function that generates a random vector of the correct size. every time you call the function, a new vector will be created. The way you are doing it now, you are creating one random vector and storing in a variable.
As a point of suggestion, I would not use a variable name of vector. It is just kind of confusing.
function out = randVec
out = 2*rand(1,3)-1;
>> randVec
ans =
-0.9286 0.6983 0.8680
>> randVec
ans =
0.3575 0.5155 0.4863
>> randVec
ans =
-0.2155 0.3110 -0.6576
You can now string these together
randMat = [randVec; randVec; randVec; randVec]
A for loop, might be better here.
Of course, if you are going to do this only to make a amtrix, why not:
randMat = 2*rand(4,3)-1;
1 个评论
Todd Flanagan
2011-1-20
George says, "Hello, Thanks a lot for the answer!
The thing that i wanted was : 2*rand(4,3)-1; ,where 4 is x.
What i was doing was that i wanted to create a matrix from am already "vector" matrix and add there x lines. But the line above does it all!"
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!