MATLAB: How to replace half the number of specific element in an array

MATLAB

Hello every one,
I have a row vector having 8236 columns, out of which 863 columns have a value 4. I want to replace 431 of the columns by a value 2. For simplicity, I am giving a vector having only 23 columns
A=[1 2 3 4 4 1 2 4 4 3 4 4 4 2 1 3 4 4 4 2 1 4 4]
Here, in this vector, there are 12 columns having a value 4. How to replace half the columns by a value 2?
Any help will be appreciated.

Best Answer

To change random columns:
>> A=[1 2 3 4 4 1 2 4 4 3 4 4 4 2 1 3 4 4 4 2 1 4 4]
A =
1 2 3 4 4 1 2 4 4 3 4 4 4 2 1 3 4 4 4 2 1 4 4
>> nnz(A==4)
ans = 12
>> idx = find(A==4);
>> num = numel(idx);
>> A(idx(randperm(num,ceil(num/2)))) = 2
A =
1 2 3 2 2 1 2 4 4 3 2 4 2 2 1 3 2 4 4 2 1 2 4
>> nnz(A==4)
ans = 6