Please include an example function call and the resulting output values from you
ID: 3593103 • Letter: P
Question
Please include an example function call and the resulting output values from your function in your comments. Loops are very useful for doing the same calculation over and over, very quickly. Let’s assume that we have a large fleet of electric cars, and we are trying to figure out how far all of them can drive. Write program that takes one input, an array of battery percentages. It should return two outputs:
- A sorted array of how far each car can drive, in descending order.
- The corresponding array of indices that maps the sorted array of distances to the original battery levels, so we can still keep track of which car is which.
This function should NOT make any actual calculations mapping battery power to distance. Instead, it should call your function from Recitation 3 Problem 2 to make those calculations. In other words, functions that contain conditional statements will lose points! Calling other built in MATLAB functions is also acceptable, and functions, like sort and length are allowed, and may be useful to you.
Recitation 3 Problrm 2
function result = car_travel(battery_amount)
%adding condition given in problem statement
if battery_amount < 100 && battery_amount >= 81 %100% and 81% charge
result = (battery_amount - 80) * 10 + 20 * 8 + 20 * 7 + 15 * 5 + 5 * 4;
elseif battery_amount < 81 && battery_amount >= 51 % Below 81% and going down to 51%
result = (battery_amount - 50) * 8 + 20 * 7 + 15 * 5 + 5 * 4;
elseif battery_amount < 51 && battery_amount >= 21 % Below 51% and going down to 21%
result = (battery_amount - 20) * 7 + 15 * 5 + 5 * 4;
elseif battery_amount < 21 && battery_amount >= 6 % Below 21% and going down to 6%
result = (battery_amount - 5) * 5 + 5 * 4;
else
result = battery_amount * 4;
end
Explanation / Answer
function result = car_travel(battery_amount)
%adding condition given in problem statement
if battery_amount < 100 && battery_amount >= 81 %100% and 81% charge
result = (battery_amount - 80) * 10 + 20 * 8 + 20 * 7 + 15 * 5 + 5 * 4;
elseif battery_amount < 81 && battery_amount >= 51 % Below 81% and going down to 51%
result = (battery_amount - 50) * 8 + 20 * 7 + 15 * 5 + 5 * 4;
elseif battery_amount < 51 && battery_amount >= 21 % Below 51% and going down to 21%
result = (battery_amount - 20) * 7 + 15 * 5 + 5 * 4;
elseif battery_amount < 21 && battery_amount >= 6 % Below 21% and going down to 6%
result = (battery_amount - 5) * 5 + 5 * 4;
else
result = battery_amount * 4;
end