Function to store values??
显示 更早的评论
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 :((
回答(3 个)
You wouldn't do it with a loop. There's a command for it,
result = randi(100,1,5)
Cris LaPierre
2020-12-12
0 个投票
Image Analyst
2020-12-12
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
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!