I need help with removing a max value from a vector so I can use the next max value

조회 수: 5 (최근 30일)
You are given an array, weights, that contains the weights of some cargo items in pounds. You want to load a truck with items from the list, up to its capacity. The truck has a maximum capacity of 1,000 pounds. For this problem use a "greedy" algorithm. That is, always load the heaviest item that will still fit on the truck. Keep loading until the remaining capcity of the truck is less than any of the remaining cargo items. For example, if the weights were { 400, 250, 700, 100, 60), you would load the 700-pound item, then the 250-pound item. The remaining items would be too heavy to fit on the truck. This problem differs from the previous one in that the weights are NOT sorted, and you may not use the sort() function.
this is what i have...
%The weights of the cargo items are generated at random
weights = randi(500, 1, randi(20))
capacity = 1000; %cargo capacity of the truck
load = 0;
remcap = 0;
next = 0;
load = max(weights);
for i = 1:length(weights)
if load <= capacity
remcap = capacity - load
for j = 1:length(weights-load)
if next <= remcap
next = remcap- max(weights)
end
end
end
end

답변 (1개)

KSSV
KSSV 2020년 2월 11일
편집: KSSV 2020년 2월 11일
YOu can use max function, this gives you index of the maximum value. You replace that value with NaN or remove it from tha array and again use max.
A = rand(1,10) ;
[val,idx] = max(A);
A(idx) = [] ;
[val,idx] = max(A) ;

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by