Create a matrix with rand
3 views (last 30 days)
Show older comments
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 Comment
Todd Flanagan
on 20 Jan 2011
George, I moved your reply to a comment in Doug's answer. You may want to accept Doug's answer if it helped you.
Answers (1)
Doug Hull
on 20 Jan 2011
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 Comment
Todd Flanagan
on 20 Jan 2011
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!"
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!