Replace elements in a row matrix randomly
Ältere Kommentare anzeigen
I have a raw matrix (1x8), which is generated randomly each time and it consists of 1s and 0s. I want to produce 3 1s each time and 5 0s. If there are less than 3 1s I want to randomly replace 0s with 1s until the number on 1s is 3. Suppose that I don't know the location of its element.
i.e : Α = [ 1 0 0 1 0 0 0 0 ]
Then the modified matrix A could be : [ 1 0 0 1 0 0 1 0 ]
0s have to be randomly replaced when needed and not to choose that with the lower index, in the matrix, to be replaced.
Any help could be useful. Thanks in advance!
1 Kommentar
Star Strider
am 3 Feb. 2015
‘Suppose that I don't know the location of its element.’
I didn’t use find in my code because I though knowing the locations of the 1s was not an option. (I deleted my Answer.)
Akzeptierte Antwort
Weitere Antworten (1)
Michael Haderlein
am 3 Feb. 2015
Is your specific algorithm necessary? I mean, that you first start with a random A and then add 1s until the condition is met? I'm asking because there's a more efficient way to do it.
It's always exactly 3 1s and 5 0s, right? Then, make it all zeros and then add some 1s:
A=zeros(1,8);
r=rand(1,8);
[~,ind]=sort(r);
A(ind(1:3))=1;
If you insist on your algorithm, I'd just create a while loop (while sum(A)<3) and then randomly put one value to 1:
A=zeros(1,8);
while sum(A)<3
A(randi([1 8]))=1;
end
2 Kommentare
Konstantinos
am 3 Feb. 2015
Michael Haderlein
am 3 Feb. 2015
That's possible, correct. But that just increases the number of loop iterations. The result will still have 3 1s. But I cannot see the benefit of this code compared to my first suggestion and to Star Strider's first code. In any case you'll get exactly 3 1s and the looping codes are most likely much more inefficient than the other ones (e.g. due to replacement of 1 by 1 = non productive iteration).
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!