looping till a condition is met.....
Show older comments
Hi;
I have an array of 2400 values. I want to loop such that i need to break into chunks till the sum becomes (say for suppose 2). i want to add 1st value plus 2nd value so on till the condition is met and then after the condition is met start adding from next number again till the condition meets.
I need chunks of values whose sum is 2 and i don't know the the exact chunks which vary by the data and the limit i set for the condition to break.
limit = 2;
s = 0;
for i = 1:length(Work)
while 1
if s >= limit
break
end
s = s + Work(i);
end
W = Work(i)
end
Accepted Answer
More Answers (1)
the cyclist
on 27 Dec 2016
Edited: the cyclist
on 27 Dec 2016
Here's one way. The core idea is that one tests whether the current value of W is over the limit, and if so then move the "pointer" index to the next element.
% Some pretend data
Work = rand(2400,1);
limit = 2;
% Preallocate
W = zeros(size(Work));
C = zeros(size(Work));
idx = 1;
for i = 1:length(Work)
C(idx) = C(idx) + 1;
if W(idx) >= limit
idx = idx + 1;
end
W(idx) = W(idx) + Work(i);
end
% Trim the excess from W and C
W(idx+1:end) = [];
C(idx+1:end) = [];
4 Comments
sri satya ravi
on 27 Dec 2016
the cyclist
on 27 Dec 2016
Did you actually try to run the code and see how it works?
At first, W(idx) = 0, true. But when that is the case, Work(i) is added to W(idx) and it is not zero anymore. That same element W(idx) will then be checked again. It's not zero anymore, and it might be over the limit now.
sri satya ravi
on 27 Dec 2016
the cyclist
on 27 Dec 2016
I've edited the code to track that in the variable C.
Categories
Find more on Numeric Types 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!