필터 지우기
필터 지우기

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

조회 수: 3 (최근 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 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