The problem I have is essentially in the title.

What I'm trying to do in Matlab is to have a set which has two elements $0$ and $2$ and to choose either $0$ or $2$ randomly and plug it into the series at some $n$.

To just generate either $0$ or $2$ I've used the following code:

r=randi([1 2],10,1)
if r==1

This was how I figured I would get either $0$ or $2$, yet I still output a $1$ as well. Is my approach even correct using the randi function or is there a more specific function to use for my purpose?

Also, if there's a way to do this without actually having to run any calculations that would be great too.

Thanks for any help or feedback!


2 Answers 2



r = randi([1,2], 10, 1)

generates a $10 \times 1$-vector of random entries, if you now compare $r$ to $1$ by r==1 this will never be true, as $r$ is a vector, not the scalar $1$, what you can do is find all 1s in $r$ and replace them by zeros doing

r(find(r==1)) = 0;

or apply a map to $r$ witch fixes 2 and maps 1 to 0 e. g.

r = 2*r - 2;
  • $\begingroup$ I see where I made my mistake, thanks for clearing it up! $\endgroup$
    – S.D.
    Commented Oct 16, 2013 at 7:12

A better way to generate the desired array is

r=2*randi([0 1],10,1)

The problem with your approach is that you try to perform a comparison on the array r, instead of each of its elements.

A way to do this would be

r(find(r==1)) = 0
  • $\begingroup$ Thanks for the response, this was definitely helpful. $\endgroup$
    – S.D.
    Commented Oct 16, 2013 at 7:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .