In: Computer Science
You have been hired by a used-car dealership to modify the price of cars that are up for sale. You will get the information about a car, and then change its price tag depending on a number of factors. Write a program (a script named: 'used_cars.m' and a function named 'car_adjust.m').The script passes the file name 'cars.dat' to the function. The following information is stored inside the file:
Ford, 2010 with 40,000 miles and no accident at marked price of $6500
Lexus, 2011 with 100,000 miles and 1 accident at marked price of $40,000
Toyota, 2008 with 20,000 miles and 2 accidents at marked price of $14,000
Audi, 2012 with 10,000 miles and no accident at marked price of $45,000
The function will open the file and store its content and creates a structure with the following fields:
Make: A string that represents the make of the car (e.g. ‘Toyota’)
Year: A number that corresponds to the year of the car (e.g. 2000)
Cost: A number that holds the cost of the car (e.g. 8000)
Price: A number that holds the marked price of the car Miles:
The number of miles clocked (e.g. 85000) Accidents:
The number of accidents the car has been in. (e.g. 1)
Your function will then return the structure to the script with all the above fields, with exactly the same names. Here is how you must calculate the Cost of each car: 1. Add 4000 to the cost if the car has clocked less than 30000 miles. 2. Subtract 2000 if it has clocked more than 90000 miles. 3. Reduce the price by 1000 for every accident. From inside your script, call different elements of the structure and make sure it returns the correct values.
%Please use Matlab R2013a or later
s = car_adjust('inp.txt');
x = size(s);
for i = 1:x(2)
c = s(i).price;
if (s(i).miles < 30000)
c = c + 4000;
end
if (s(i).miles > 90000)
c = c - 2000;
end
r = s(i).accident*1000;
c = c -r;
s(i).cost = c;
fprintf('Cost of car %d = $%.2f\n',i,c);
end
function [s] = car_adjust(file)
f = fopen(file,'r');
s = [];
while ~feof(f)
line = fgets(f);
s1 = strsplit(line,', ');
make = s1(1);
s2 = strsplit(line);
year = s2(2);
c1=strsplit(line,'$');
miles = s2(4);
acc = s2(7);
if (strcmp(acc,'no'))
accident = 0;
else
accident = str2double(acc);
end
str =
struct('make',make,'year',str2double(year),'price',str2double(c1(2)),'accident',accident,'miles',str2double(miles),'cost',0);
s = [s str];
end
end