How to use a loop to add a value at an increasing interval
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Thomas
el 30 de Mzo. de 2016
Comentada: Thomas
el 30 de Mzo. de 2016
Hi, I am trying to calculate the cost of a range of values where there is a linear cost per each unit and a separate cost per 100 units. The linear cost per unit is simple but I am trying to use a range that updates per each iteration by incorporating this into a while loop and an IF statement. I could really use some advice as I keep running into problems. There is an example of the code I am using below.
%
costpu = 320; % cost per unit
costsy = 20000; % cost per 100 units
units = linspace(100,4000,36); % row vector of units
n = 0;
m = 100; % m and n are the starting range
p = 1;
idx = 1;
while n < units(end)
if units(idx) > n & units(idx) < m
cost(idx) = (units(idx)*costpu) + (costsy*p)
end
n = n + 100;
m = m + 100; % increasing the range per each iteration
p = p + 1; %
idx = idx + 1;
end
If any one has some advice or an alternative approach to this problem I would really appreciate it.
Thanks.
1 comentario
Jan
el 30 de Mzo. de 2016
I do not understand the question. What exactly does "use a range that updates per each iteration by incorporating this into a while loop and an IF statement" mean? What did you try an in which troubles did you run?
Respuesta aceptada
Robert
el 30 de Mzo. de 2016
If I gather correctly what you are trying to do, you don't need the loop at all. You can determine the total cost for any number of units as shown below.
costpu = 320; % cost per unit
costsy = 20000; % cost per 100 units
units = linspace(100,4000,36); % row vector of units
cost = costpu*mod(units,100) + costsy*floor(units/100);
plot(units,cost)
Note that mod returns the number of units that don't make an even hundred and floor gives you the number of sets of 100.
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!