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

2 ビュー (過去 30 日間)
Thomas
Thomas 2016 年 3 月 30 日
コメント済み: Thomas 2016 年 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.
  1 件のコメント
Thomas
Thomas 2016 年 3 月 30 日
Ah! Thank you very much. That has helped a great deal.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by