MATLAB: How to end a for loop when a specific value is reached and create a new array with data that meets that condition

for loop

I'm trying to simulate the loss of the highest values in a dataset. My end goal is to create a new array that matches the mean of observed data — i.e. I need to calculate means for modeled values in cells 1-2, 1-3, 1-4… 1-n until I find the range of modeled values with a mean that matches my observed data. Right now, I'm trying to work with a for loop that will terminate once a mean threshold is met — when that threshold is met, I would like to create a new array (rh2 in my code) that incorporates the cells used to calculate the modeled mean that best matches my observed mean. My code seems giving me output of a modeled mean that matches my observed mean, but not the output of the array that I need. Thanks!
meanr2 = mean(ruber2);
ko = fitdist(ruber1,'kernel');
ruber = ko.random(500,1);
sort_ruber = sort(ruber);
for k=1:500
mur = mean(sort_ruber(1:k));
if mur <= meanr2
rh2 = ruber(1:k);
elseif mur > meanr2
return
end
end

Best Answer

actually your answer helped me figure it out -- thank you! I need to output the sort_ruber rather than the ruber.