Need help using a for loop

1 vue (au cours des 30 derniers jours)
James Bell
James Bell le 30 Avr 2011
My program reads data from a file column 1 is an ID number, column 2 is a weight, column 3 is the priority. Supplies must be loaded on to a ship (capacity 60 tons) by priority.
On the second for loop I would like to start the loop where my computed ID's end (not 1). (So i can search for the remaining weight needed by priority without finding an ID that i already have).
With that being said, any other advice to make my code more efficient would be greatly appreciated.
function [] = Supplies(filename)
%A = load(filename);
A = load('data1.txt'); % TESTING
A = sortrows(A,-3);
%p = A(:,3); %Priority of supply
%w = A(:,2); %Weight of supply
%id = A(:,1); %ID of supply
tons = 0;
tonsN=0;
ID = zeros(1);
cnt =1;
for i = 1:1000
if (tons < 60)
tonsN = A(i,2);
tons = tons + tonsN;%TESTING
ID(cnt) = [ A(i,1)];
cnt = cnt+1;
else
ID(end)=[];
%disp(ID')TEST
tons = tons - tonsN;%TESTING
break
end
end
tonsNEED = 60-tons;
tons%TEST
tonsNEED%TEST
for i = 1:1000
if A(i,2) == tonsNEED
ID(end+1) = A(i,1);
break
end
end
disp(ID') %TEST
end
%First, my code sorts the supplies by priority, highest to lowest, using sortrows.
%Then, through a for loop, the weights are added, starting from highest
%priority, untill it is greater than 60. Once greater than 60 I subtract the
%last item so it is within the 60 ton limit. To find a supply to fit the
%remaining capacity, another for loop is used to find a weight that matches
%the weight needed by priority

Réponses (1)

Héctor Corte
Héctor Corte le 11 Jan 2012
Your first for should be:
for i=1:length(A(:1))
and your second for should be:
for i=length(ID):length(A(:1))
And the if inside the second for should have < instead of ==.
You can precharge variable ID to make code faster, but then you need other for loops.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by