Clear Filters
Clear Filters

Replace percentage of data in a for loop

3 views (last 30 days)
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 Comments
Geoff Hayes
Geoff Hayes on 6 Jun 2017
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 on 6 Jun 2017
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!

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 6 Jun 2017
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 Comments
Tracy Campbell
Tracy Campbell on 14 Jun 2017
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 on 14 Jun 2017
The line
data(which_to_replace, 3) = 16;
does the replacement.

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!