disp('Howdy Folks')
a = input('Enter a Number to Square ');
b = a*a;
disp(['The Result is ' num2str(b)])
Now type test1 in the Matlab window and it will ask
for a number, square it and then display the result.
Reserve = 100; % Initial amount in the Reservoir
LossRate = 0.2; % Rate at which material flows from reservoir
for i=1:20; % Perform the following statements 20 times
OutFlow = LossRate*Reserve; % Calculate the amount of snow that melts
Reserve = Reserve - OutFlow; % Subtract this from the reserve
disp(['After Day ' num2str(i) ' Outflow=' num2str(OutFlow) ...
' Reserve=' num2str(Reserve)]);
end % for i ...
Note that this program will run the loop a total of 20 times.
To make the program more readable, there are
a few rules you may wish to follow:
if Reserve < 30
LossRate = 0.3;
else
LossRate = 0.2;
end % if Reserve...
The placement of this block is very important - the value of
LossRate
is only changed when these commands are executed, thus if this block
is placed immediately before the for statement, the value
of LossRate will always be 0.2. To make this work correctly,
this block of commands should be inserted after the for
statement but before the OutFlow calculation, so it will
always have the correct value for LossRate.
Put these changes into your program.
It would also be nice to make a plot of the Reservoir and the Melting rate as a function of time. We can do this by appending the current values onto the end of a list of the previous values. A script file meltplot.m to do this would be
Reserve = 100; % Initial amount in the Reservoir
AllReserve = []; % Make an empty array to hold the Reservoir values
AllOutFlow = [];
for i=1:20; % Perform the following statements 20 times
if Reserve < 30
LossRate = 0.3;
else
LossRate = 0.2;
end % if Reserve...
OutFlow = LossRate*Reserve; % Calculate the amount of snow that melts
Reserve = Reserve - OutFlow; % Subtract this from the reserve
disp(['After Day ' num2str(i) ' Outflow=' num2str(OutFlow) ...
' Reserve=' num2str(Reserve)]);
AllReserve = [AllReserve Reserve];
AllOutFlow = [AllOutFlow OutFlow];
end % for i ...
hold off
plot (AllReserve,'g-')
hold on
plot (AllOutFlow,'r-')
We could even extend the model further by saying that if the Reservoir
is less than 10, it all melts immediately. We could do this
using the if-elseif structure.
Modify your program to do this.