Replace percentage of data in a for loop

3 次查看(过去 30 天)
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