In: Computer Science
The electricity accounts of residents in a very small rural community are calculated as follows: a. if 500 units or less are used the cost is 2 cents per unit; b. if more than 500, but not more than 1000 units are used, the cost is $10 for the first 500 units, and then 5 cents for every unit in excess of 500; c. if more than 1000 units are used, the cost is $35 for the first 1000 units plus 10 cents for every unit in excess of 1000; d. in addition, a basic service fee of $5 is charged, no matter how much electricity is used. The five residents use the following amounts (units) of electricity in a certain month: 200, 500, 700, 1000, and 1500. Write a program which uses logical vectors to calculate how much they must pay. Display the results in two columns: one for the electricity used in each case, and one for amount owed. (Answers: $9, $15, $25, $40, $90)
::Matlab Code::
Using Logical vectors to calculate payment instead of else-if ladders, the code looks like this-
% logical vectors
unit = [200 500 700 1000 1500];
bill = 10 * (unit > 500) + 25 * (unit > 1000) + 5;
bill = bill + 0.02 * (unit <= 500) .* unit;
bill = bill + 0.05 * (unit > 500 & unit <= 1000) .* (unit - 500);
bill = bill + 0.1 * (unit > 1000) .* (unit - 1000);
fprintf("\t Units \t Charge(in $) \n");
disp( [unit' bill'] );
Output of above program:
Refer to the screenshot below for better understaning of code indentaion -