How to get Random numbers only from -1 1 and 2?

2 Ansichten (letzte 30 Tage)
Ege Tunç
Ege Tunç am 26 Dez. 2018
Bearbeitet: Stephen23 am 27 Dez. 2018
I need to create a random integer numbers generator which only creates -1,1 and 2
here is my code for 1 or 2:
for m=1:100
A=randi([-1 2]);
A
end

Akzeptierte Antwort

Stephen23
Stephen23 am 26 Dez. 2018
The easiest way is to define a vector of the values that you want and use (random) indexing:
>> V = [-1,1,2];
>> V(randi(numel(V),1,12))
ans =
-1 2 1 2 -1 2 -1 1 -1 2 -1 1
  4 Kommentare
madhan ravi
madhan ravi am 27 Dez. 2018
Bearbeitet: madhan ravi am 27 Dez. 2018
Nah... atleast you could have added a note that it was taken from the other. I‘m pretty sure if it would have happened the other way around , you would have handled it differently..
Stephen23
Stephen23 am 27 Dez. 2018
Bearbeitet: Stephen23 am 27 Dez. 2018
"atleast you could have added a note that it was taken from the other"
This is the same answer that has been given many times before to the same question:
I did not notice your answer: I usually open many tabs in my browser and work through them. If anyone adds something (or deletes the question) in the meantime I would not know about it until after posting any answer or comment and then refreshing the page, which could be half an hour or more since opening that tab. If the page is not refreshed then I do not see any other additions, and have usually moved on to the next tab anyway.
"I‘m pretty sure if it would have happened the other way around , you would have handled it differently"
If I notice that I have submitted exactly the same answer as an earlier answer then usually I delete my answer. If there are distinctions that I consider might be useful for the OP (e.g. references, explanations, examples, etc., which I try to include where relevant) then I might leave my answer and hope that it will be of use to the OP. As often we have no idea of the level of experience or level of interest of the OP this can be useful: some are looking for a quick-fix, while others are looking to learn and understand. Different answers, even with much the same code, cater to different tastes and needs of the OPs. As you have noticed I try to explain and give references where this might be useful. And apparently some OPs do find this useful.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

madhan ravi
madhan ravi am 26 Dez. 2018
P=[-1 1 2];
A=P(randi([1 numel(P)],1,100))

Kategorien

Mehr zu Random Number Generation finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by