Function to store values??
Show older comments
Which would be a function to store values from a loop?
For example
I want to get a random number from 1 to 100
I get any number and i want to store that number in a vector
Choose any other random number again
And I want to store that number with the last one I got
And repeat
I just want to know which function to use
Im bad a coding and idk how to explain more clearly :((
Answers (3)
You wouldn't do it with a loop. There's a command for it,
result = randi(100,1,5)
Cris LaPierre
on 12 Dec 2020
0 votes
Image Analyst
on 12 Dec 2020
Not sure what "store that number with the last one I got" means. Do you want a 2 column array with column 1 being the first number and column 2 being the second number? Matt's solution about using rand() is good and for 2 columns you'd do this:
numRows = 40; % Whatever
randomValues = rand(numRows, 2);
If you insisted on using a loop to build it, then you'd do this:
numRows = 40; % Whatever
for row = 1 : numRows
randomValues(row, 1) = rand(1); % Generate a single random number and store in column 1.
randomValues(row, 2) = rand(1); % Generate a second single random number and store in column 2.
end
Or if you wanted two vectors instead of a matrix, you could do
numRows = 40; % Whatever
for row = 1 : numRows
vec1(row) = rand(1); % Generate a single random number and store in vector vec1.
vec2(row) = rand(1); % Generate a second single random number and store in vector vec2.
end
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!