How to save while loop values in multiple arrays of different length to merge if condition if met
3 次查看(过去 30 天)
显示 更早的评论
Hi,
I have this code at the moment that loops through a list of values (customer demands from 2 customers being merged) from top to bottom and sums the values into an accumulated sum, breaks the accumulated sum when a specific threshold is reached (37) and then starts over the accumulated sum from the next number in the list. For example, the list of 14 14 12 12 6 6 12 12 20 is becoming 14 28 [break] 12 24 30 36 [break] 12 24 [break] 20 [break].
x = Sum_efterfr_SavingList_kol6; % the list of values
threshold = 37;
index=1;
while 1
xc = cumsum(x(index:end));
m = find(xc > thresh,1,'first');
if isempty(m)
break
end
x(m) = x(m)-xc(m-1);
Loopdata{m}=xc; % this is not saving the values that i want, only where in the list that the cumsum is starting over
end
My first problem is partly that I want to save each accumulated sum into individual arrays instead of a long list, for example I want A = (14 28), B = (12 24 30 36) and so on, but I can't get it to work properly.
But I also can't figure out how (and where in the while loop) to implement that I only want to use the cumsum on the values of customers that isn't already part of a saved array, because I aim to eventually execute the Clarke & Wright algoritm with merging customers in tours (the saved arrays will eventually be the tours) and the list with cumsums will not loop from top to bottom.
Would really appreciate some help!
0 个评论
采纳的回答
Raunak Gupta
2020-5-30
Hi,
Below code might help you. Here I am finding the first index in cumulative sum where the value is greater than threshold and then taking the array upto that point. For next time I am subtracting the value accumulated till the current index so that next time we will start from next index in array and doing the same process until the end of array.
Hope you will understand the code.
x = randi(15,[20,1]);
threshold = 37;
totalSum = cumsum(x);
index = 1;
% final count will be total number of partition in the array
count = 1;
Loopdata = {};
while index <= length(x)
% First index in the array where value > threshold
newIndex = find(totalSum>threshold,1);
if isempty(newIndex)
% for last index take the full array till the end
Loopdata{count} = cumsum(x(index:end));
break;
else
% Take the array upto newIndex - 1 because value exceeds threshold
% at newIndex
% Here predefining Loopdata can be handy but we don't know the size
Loopdata{count} = cumsum(x(index:newIndex-1));
% Subtracting the current accumulated value so that next time the
% index start from newIndex
totalSum = totalSum - totalSum(newIndex-1);
index = newIndex;
count = count + 1;
end
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!