Effacer les filtres
Effacer les filtres

How to use a loop to add a value at an increasing interval

3 vues (au cours des 30 derniers jours)
Thomas
Thomas le 30 Mar 2016
Commenté : Thomas le 30 Mar 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 commentaire
Jan
Jan le 30 Mar 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?

Connectez-vous pour commenter.

Réponse acceptée

Robert
Robert le 30 Mar 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.
  1 commentaire
Thomas
Thomas le 30 Mar 2016
Ah! Thank you very much. That has helped a great deal.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

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

Community Treasure Hunt

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

Start Hunting!

Translated by