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

3 次查看(过去 30 天)
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 个评论
Jan
Jan 2016-3-30
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?

请先登录,再进行评论。

采纳的回答

Robert
Robert 2016-3-30
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by