Replace elements in a row matrix randomly

3 Ansichten (letzte 30 Tage)
Konstantinos
Konstantinos am 3 Feb. 2015
Kommentiert: Star Strider am 3 Feb. 2015
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
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.)

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Guillaume
Guillaume am 3 Feb. 2015
How about:
zeroidx = find(~A); %find position ot 0s
replaceidx = zeroidx(randperm(numel(zeroidx), 3-sum(A))); select random 0s to replace
A(replaceidx) = 1;
This assumes there's never more than three 1 in A, which I think is your case since you never mention replace 1 with 0.

Weitere Antworten (1)

Michael Haderlein
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
Konstantinos am 3 Feb. 2015
Your second code seems to be correct for my case. But there is a chance that the 1 could replace another 1. So the number of 1s will remain 2.
Michael Haderlein
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).

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating and Concatenating Matrices 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