Help with writing a matlab code

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 3K views
alas
Messages
2
Reaction score
0
?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.
 
Physics news on Phys.org
Here is a recursive function that will do what you want:
Code:
[b]function[/b][/color] [/color][ v, i ] =  [/color]randomOnesZeros[/color](v, i)
    [/color]maxIter = 10; [i]% change this to what you want[/i][/color]
    maxLength = 10; [i]% change this to what you want[/i][/color]
    r = rand[/color]();
    r = mod[/color](floor[/color]((r *[/color] maxLength)), maxLength);
    [b]if[/b][/color] i[/color] <[/color]= maxIter
        [b]if[/b][/color] mod[/color](i[/color], 2)
            zeros[/color](1, r);
            v = [v zeros[/color](1, r)];
        [b]else[/b][/color]
            v = [v ones[/color](1, r)];
        [b]end[/b][/color]
        [v, i[/color]] = randomOnesZeros(v, i[/color] +[/color] 1);
    [b]end[/b][/color]
[b]end[/b][/color]
In this function, we have two variables, [itex]\mathbf{v}[/itex] and [itex]i[/itex]. [itex]\mathbf{v}[/itex] is your vector and [itex]i[/itex] 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 [itex]r \in [0, {\tt maxLength}][/itex].

If the iteration is even, we append a [itex]1 \times r[/itex] vector of zeros to our vector, otherwise we append a [itex]1 \times r[/itex] 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 = rand[/color](1, n);
vector = (r >[/color] 0.5) *[/color] zeros[/color](1, n) +[/color] (r <[/color] 0.5) *[/color] ones[/color](1, n);
This creates a vector [itex]\mathbf{r} = \langle r_1, r_2, \ldots , r_n\rangle[/itex] of random values s.t. [itex]r_i \in [0,1][/itex]. 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