필터 지우기
필터 지우기

Replace percentage of data in a for loop

조회 수: 3 (최근 30일)
Tracy Campbell
Tracy Campbell 2017년 6월 6일
댓글: Walter Roberson 2017년 6월 14일
Hello,
I'm hoping to find out how to replace a defined percentage of data? I'm currently using a for loop with an if statement and would like to add another component quantifying the percentage replaced.
This is my current code:
for i=1:53280
LULC1=data(i,21);
LCC=data(i,20);
if LULC1==12||LULC1==15
data(i,3)=16;
end
end
  댓글 수: 2
Geoff Hayes
Geoff Hayes 2017년 6월 6일
Tracy - please clarify what you mean by how to replace a defined percentage of data. In your above code, is it a certain percentage of the elements of data that will be replaced? So once you reach that percentage then you can exit the for loop?
Tracy Campbell
Tracy Campbell 2017년 6월 6일
I am hoping to replace 15%, 25%, and 50% of the data that fits the conditions listed in the if statements. Any help is appreciated!

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2017년 6월 6일
percent_to_replace = 17.3; %for example
row_matches = find( ismember(data(:,21), [12 15]) );
num_matches = length(row_matches);
num_to_replace = round(num_matches * percent_to_replace / 100);
which_to_replace = row_matches( randperm(num_matches, num_to_replace) );
data(which_to_replace, 3) = 16;
This uses the percentage as a fixed percentage to replace, that to within round-off, exactly that portion will be replaced. There is an alternative to that, which is to treat the percentage as a probability that any given one will be replaced.
percent_to_replace = 17.3; %for example
which_to_replace = ismember(data(:,21), [12 15]) & (rand(size(data,1),1) < percent_to_replace/100);
data(which_to_replace, 3) = 16;
This would replace the given percentage on average
  댓글 수: 2
Tracy Campbell
Tracy Campbell 2017년 6월 14일
Thank you so much for the answer. I have a follow-up question. When I run the script, it provides me with the information in which rows fit the description, but does not actually replace the data. Am I missing something? Thank you.
Walter Roberson
Walter Roberson 2017년 6월 14일
The line
data(which_to_replace, 3) = 16;
does the replacement.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by