필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
abdur rauf
abdur rauf 2018년 6월 18일
편집: Stephen23 2018년 6월 18일
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.

채택된 답변

Stephen23
Stephen23 2018년 6월 18일
편집: Stephen23 2018년 6월 18일
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

추가 답변 (2개)

KALYAN ACHARJYA
KALYAN ACHARJYA 2018년 6월 18일
편집: KALYAN ACHARJYA 2018년 6월 18일
A=[1 2 3 4 4 1 2 4 4 3 4 4 4 2 1 3 4 4 4 2 1 4 4];
for i=1:length(A)/2;
if A(i)==4
A(i)=2;
end
end

Ameer Hamza
Ameer Hamza 2018년 6월 18일
편집: Ameer Hamza 2018년 6월 18일
Here is one possible solution
A=[1 2 3 4 4 1 2 4 4 3 4 4 4 2 1 3 4 4 4 2 1 4 4];
index = find(A==4);
randomIndex = randperm(length(index));
A(index(randomIndex(1:end/2))) = 2;
it will randomly select which columns to change.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by