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 :((

Réponses (3)

Matt J
Matt J le 12 Déc 2020
Modifié(e) : Matt J le 12 Déc 2020

0 votes

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 le 12 Déc 2020

0 votes

I suggest going through MATLAB Onramp. Ch 5 and Ch 13 are probably of particular relevance here.
Image Analyst
Image Analyst le 12 Déc 2020

0 votes

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

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by