How to choose a single element randomly from a vector
31 views (last 30 days)
Show older comments
A=[2 3 4 5];
How do I choose any one variable from the vector A randomly each time.
0 Comments
Accepted Answer
R
on 3 Aug 2024
Hi @Yogesh
To choose a random element from the vector A each time in MATLAB, you can use the randi function to generate a random index and then use that index to access an element from A.
See below:
A = [2 3 4 5];
randomElement = A(randi(length(A)));
disp(randomElement);
This code will select and display a random element from the vector A each time it is run.
To know more about random number generation, refer to: Random Number Generation - MATLAB & Simulink (mathworks.com)
More Answers (1)
John D'Errico
on 3 Aug 2024
Edited: John D'Errico
on 3 Aug 2024
I've upvoted the answer by @R. Please accept it. My answer here is only to express some ideas that are really best put in a comment to that answer, but comments often get lost.
When you have a problem you can't solve, one too big of a step to make for your current skills, break it into smaller pieces. Look for ways to approach a solution, in smaller chunks. Always remember to eat a programming elephant one byte at a time.
For example, consider the vector V.
V = [2 3 5 7 11 13 17 19];
Here, a list pf prime numbers. Suppose I want to generate a random prime from that list? First, how do you extract one element? What, for example is the 5th element from that vector?
V(5)
So we know how to index into a vector. Does this help us in any way? Well, possibly. Is there some way we can generate a random index? There are 8 elements in the vector V.
nV = numel(V)
Suppose we could generate a random integer, from the set 1 through 8? Could we then use that number as an index into V?
What tools are there in MATLAB to generate random numbers? The big three are rand, randn, and randi. Of those three, rand and randn generate numbers from continuous distributions, thus uniform and Gaussian. They are not directly useful here. (though with some effort, we could use rand.) But randi should seem useful.
help randi
Do you see that randi can generate random integers from the set 1:nV?
randi(nV)
randi(nV)
Does that help? I hope so. Use indexing to give you what you need.
ind = randi(nV)
V(ind)
The point is, to look for tools that might help you to get at least closer to a solution. Then think about how you might use them, sometimes in combination with oher tools you already know how to use, to then solve your problem.
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices 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!