rounding function for converting it to an integer value.
Show older comments
I am a beginner to MATLAB. I am trying to solve one of the problems from the book I am practicing MATLAB and the problem is
Imagine that you are the owner of a car rental company with two locations, Albany and Boston. Some of your customers
do “one-way rentals,” picking up a car in Albany and returning it in Boston, or the other way around. Over time, you
have observed that each week 5% of the cars in Albany are dropped off in Boston, and 3% of the cars in Boston get
dropped off in Albany. At the beginning of the year, there are 150 cars at each location.
Write a script called car update that updates the number of cars in each location from one week to the next. The
precondition is that the variables a and b contain the number of cars in each location at the beginning of the week.
The postcondition is that a and b have been modified to reflect the number of cars that moved.
To test your program, initialize a and b at the prompt and then execute the script. The script should display the
updated values of a and b, but not any intermediate variables.
Note: cars are countable things, so a and b should always be integer values. You might want to use the round function
to compute the number of cars that move during each week.
If you execute your script repeatedly, you can simulate the passage of time from week to week. What do you think will
happen to the number of cars? Will all the cars end up in one place? Will the number of cars reach an equilibrium, or
will it oscillate from week to week?
I wrote a code for the problem.
% companies at two places Albany and Boton are represented as A and B%
j1=150;
j2=150;
i=1;
u(i)=j1-(5/100)*j1+(3/100)*j2;
j1=round(u(i)); %From A to B
u(i)=j2-(3/100)*j2+(5/100)*j1; %from B to A
j2=round(u(i));
disp('week Car at A Car at B')
fprintf('%.0f\t\t %.0f\t\t %.0f\t\t \n',i,j1,j2)
for i=2:30
u(i)=j1-(5/100)*j1+(3/100)*j2;
j1=round(u(i)); %From A to B
u(i)=j2-(3/100)*j2+(5/100)*round(u(i-1)); %from B to A
j2=round(u(i));
fprintf('%.0f\t\t %.0f\t\t %.f\t\t\n',i,j1,j2)
if j1==0
break;
end
end
But the problem I get is for the first three results,they are okay as the total number of cars after update is conserved. But may be because of the rounding process,the total number of cars is not equal to 300 (i.e 150+150). I don't understand where have I gone wrong or how do I solve it. Anyway who could suggest me a correct way to solve the problem? And also help me with the last question,what will happen to the number of cars?
Accepted Answer
More Answers (0)
Categories
Find more on Code Performance in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!