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 个)

Matt J
Matt J 2020-12-12
编辑:Matt J 2020-12-12
You wouldn't do it with a loop. There's a command for it,
result = randi(100,1,5)
result = 1×5
95 75 86 82 56
Cris LaPierre
Cris LaPierre 2020-12-12

0 个投票

I suggest going through MATLAB Onramp. Ch 5 and Ch 13 are probably of particular relevance here.
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!

Translated by