フィルターのクリア

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 Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by