I don't understand something

2 visualizaciones (últimos 30 días)
googo
googo el 22 de Mzo. de 2013
Hey!
I'm trying to write a program which take two matrices when one is a type of coin(for exmple: 1 cent, 2 cent etc) and frequency the second matrix tells how much each coin weigh. The function returns the weight of the total coins. If a specific weight of a coin isn't mentioned in the wtable the function returns -1.
This is what I wrote:
function tw=totalWeight(ftable,wtable)
tw=0;
for i=1:size(ftable,1)
c=0;
for j=1:size(wtable,1)
if wtable(j,1) == ftable(i,1)
c=ftable(i,2)* wtable(j,2);
tw=tw+c;
end
end
if c==0
tw=-1;
end
end
end
Now, I don't understand something. Here the function returns -1 (no information about "17" coin weight)
totalWeight ([1 10; 17 3],[1 5; 2 10; 5 17])
ans -1
but why here totalWeight ([1 10; 2 3;10 4;5 3],[1 5; 2 10; 5 17]) the function returns ans = 50... the wtable doesn't tell how much the "10" coin weigh... it should return -1
the wtable doesn't have to tell the minimum information (meaning it can tell me how much 20 coin weigh and 50 coins weigh although it isn't necessary but should contain all the information about the coins in the ftable...
thank you very much for your help.

Respuestas (1)

the cyclist
the cyclist el 22 de Mzo. de 2013
Editada: the cyclist el 22 de Mzo. de 2013
When you don't find a particular coin in your weight table, you set tw=-1, but then you continue along with the next coin (accumulating the total weight from a new starting point of -1).
Instead, exit the function after you determine you are missing information for that coin:
if c==0
tw=-1;
return
end

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by