Help with writing a matlab code

• MATLAB
?hi,
im trying to write a code that should do this-
create a random sized zeros vector
create a random size ones vector
i have to do this several times and combine it all(by that order) into one vector that should lookz like-
0000011111001111001...
does anybosy have an idea how to do it without using any loop?

thanks.

Related MATLAB, Maple, Mathematica, LaTeX News on Phys.org
jhae2.718
Gold Member
Here is a recursive function that will do what you want:
Code:
[color=#008000][b]function[/b][/color][color=#bbbbbb] [/color][ v, i ] = [color=#bbbbbb] [/color][color=#0000FF]randomOnesZeros[/color](v, i)[color=#bbbbbb]
[/color]maxIter = 10; [color=#408080][i]% change this to what you want[/i][/color]
maxLength = 10; [color=#408080][i]% change this to what you want[/i][/color]
r = [color=#008000]rand[/color]();
r = [color=#008000]mod[/color]([color=#008000]floor[/color]((r [color=#666666]*[/color] maxLength)), maxLength);
[color=#008000][b]if[/b][/color] [color=#008000]i[/color] [color=#666666]<[/color]= maxIter
[color=#008000][b]if[/b][/color] [color=#008000]mod[/color]([color=#008000]i[/color], 2)
[color=#008000]zeros[/color](1, r);
v = [v [color=#008000]zeros[/color](1, r)];
[color=#008000][b]else[/b][/color]
v = [v [color=#008000]ones[/color](1, r)];
[color=#008000][b]end[/b][/color]
[v, [color=#008000]i[/color]] = randomOnesZeros(v, [color=#008000]i[/color] [color=#666666]+[/color] 1);
[color=#008000][b]end[/b][/color]
[color=#008000][b]end[/b][/color]
In this function, we have two variables, $\mathbf{v}$ and $i$. $\mathbf{v}$ is your vector and $i$ is a counter for the number of iterations. We set a value for the max length of zeros or ones to add, and a maximum number of iterations for the function. Then, we compute a random integer $r \in [0, {\tt maxLength}]$.

If the iteration is even, we append a $1 \times r$ vector of zeros to our vector, otherwise we append a $1 \times r$ vector of ones to our vector.

Then, if we are below the maximum number of iterations, we recursively call our function, making sure to save the return value in the current scope.

For just a random vector of ones and zeros, you could use a statement like:
Code:
r = [color=#008000]rand[/color](1, n);
vector = (r [color=#666666]>[/color] 0.5) [color=#666666]*[/color] [color=#008000]zeros[/color](1, n) [color=#666666]+[/color] (r [color=#666666]<[/color] 0.5) [color=#666666]*[/color] [color=#008000]ones[/color](1, n);
This creates a vector $\mathbf{r} = \langle r_1, r_2, \ldots , r_n\rangle$ of random values s.t. $r_i \in [0,1]$. In the next statement, we compare an element of the vector to the value of the center of the interval, 0.5. If it's larger than 0.5, we set the element to 0 and if it's smaller than 0.5 we set that value to 1.

Last edited:
thank you, i really think it'll help me

jhae2.718
Gold Member
There's a more efficient way to implement it, but that's for you to figure out. Some MATLAB resources are: