Azzera filtri
Azzera filtri

Replace percentage of data in a for loop

1 visualizzazione (ultimi 30 giorni)
Tracy Campbell
Tracy Campbell il 6 Giu 2017
Commentato: Walter Roberson il 14 Giu 2017
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 Commenti
Geoff Hayes
Geoff Hayes il 6 Giu 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 il 6 Giu 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!

Accedi per commentare.

Risposte (1)

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

Accedi per commentare.

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by