MATLAB: Replace elements in a row matrix randomly

elementsmatrixreplacerow matrix

I have a raw matrix (1×8), 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!

Best Answer

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.
Related Question