MATLAB: Replacing duplicates in a vector of required length

duplicatesvector

Hi there, I am simulating events of different durations and am stuck about how to replace duplicate values in my vector. This is what I have so far:
To create 14 events that occur for a range of 120 to 300 seconds (the total number seconds of all 14 events must add up to 2880 seconds).
du=round(randfixedsum(14,1,2880,120,300))
To generate start times for each event:
st=randperm(28800,14)
duration = du’
m = cumsum(duration);
t = m – duration + 1; s = zeros(1,m(end));
s(t) = 1;
ii = cumsum(s);
out = (1:m(end)) – t(ii) + st(ii);
sort(out)'
out=unique(out)
I end up with a list of seconds during which these events are occurring, but the total seconds now falls short of the required (2880s) as I have removed the duplicates. How do I replace these duplicates so that all the requirements are met (i.e., all the variables in this – du=round(randfixedsum(14,1,2880,120,300)).
I hope this makes sencec, any help is greatly appreciated!

Best Answer

If you are not concerned with duplicates in 'du', here is a method which only calls on 'randfixedsum' once, but adjusts an offset so as to obtain the desired sum when rounded to integers:
x = randfixedsum(14,1,2880,120,300);
tp = .5; tm = -.5;
for k = 1:53
t0 = (tp+tm)/2;
du = round(x+t0); % Round with offset
e = sum(du)-2880;
if e > 0, tp = t0;
elseif e < 0, tm = t0;
else break % Break out when sum is correct
end
end
The same would apply to the calculation I recommended for the intervals between "events" for which you might presumably call on 'randfixedsum' with:
x = randfixedsum(15,1,25920,0,25920);
(or perhaps you have some other constraint to place on these intervals between "events" tnan merely lying between 0 and 25920.)