CS 100: Lecture L21

April 13

| Back to Lecture Index |


Assume the availability of this function:

  
  function D = D98
% Yields a 2-by-365 matrix D.
% For i=1:365, D(1,i) the high temperature for day i in 1998, and
% D(2,i) the low temperature for day i in 1998.
% Days are indexed from 1 (= Jan 1) to 365 (= December 31)

 

% Script File: L5

nSpring = EnergyDays(80,172);
nSummer = EnergyDays(173,264);
nAutumn = EnergyDays(265,355);
[L_Spring,H_Spring] = AveHiLo(80,172);
[L_Summer,H_Summer] = AveHiLo(173,264);
[L_Autumn,H_Autumn] = AveHiLo(265,355);
clc
disp('        EnergyDays  Ave Low  Ave High')
disp('-------------------------------------')
disp(sprintf(' Spring     %2d     %6.1f    %6.1f',nSpring,L_Spring,H_Spring))
disp(sprintf(' Summer     %2d     %6.1f    %6.1f',nSummer,L_Summer,H_Summer))
disp(sprintf(' Autumn     %2d     %6.1f    %6.1f',nAutumn,L_Autumn,H_Autumn))

EnergyDays: loop-free implementation

  function n = EnergyDays(d1,d2)
% 1<=d1<=d2<=365.
% n is the number of energy days from day d1 through day d2.

T = D98;
days = d1:d2;
n = sum(T(1,days)>85 | T(2,days)< 50);

EnergyDays: loop version

  function n = EnergyDays(d1,d2)
% 1<=d1<=d2<=365.
% n is the number of energy days from day d1 through day d2.

T = D98;
n=0;
for i=d1:d2
   if (T(1,i)>85) | (T(2,i) < 50)
      n=n+1;
   end
end

AveHiLo: Loop-free version

  function [Lo,Hi] = AveHiLo(d1,d2)
% 1<=d1<=d2<=365.
% Lo is the average low  temperature from day d1 through day d2.
% Hi is the average high temperature from day d1 through day d2.

T = D98;
days = d1:d2;
n = d2-d1+1;
Hi = sum(T(1,days))/n;
Lo = sum(T(2,days))/n;

AveHiLo: Loop version

  function [Lo,Hi] = AveHiLo(d1,d2)
% 1<=d1<=d2<=365.
% Lo is the average low  temperature from day d1 through day d2.
% Hi is the average high temperature from day d1 through day d2.

T = D98;
n = d2-d1+1; 
Hi = 0; Lo = 0;  
for i=d1:d2
   Hi = Hi + T(1,days);
   Lo = Lo + T(2,days);
end
Hi = Hi/n;
Lo = Lo/n;

Example L6 (Loop-Free Version)

% Script File: L6
D = D98;
spring = 80:173;
lows = D(2,spring);
n = length(lows);
days = 1:n;

plot(days,lows,days,lows,'xk')
pause

hold on

WarmDays = find(lows>50);
plot(WarmDays,lows(WarmDays),'hr')
pause

diff = lows(2:n)-lows(1:n-1);
idx = find(diff>5)+1;
plot(idx,lows(idx),'or')

hold off

Example L6 (Loop Version)

 
% Script File: L6
D = D98;
spring = 80:173;
lows = D(2,spring);
n = length(lows);
days = 1:n;

plot(days,lows,days,lows,'xk')
pause

hold on

for i=1:n
   if lows(i)>50
      plot(i,lows(i),'hr')
   end
end
pause

for i=2:n
   if lows(i)-lows(i-1)>5
      plot(i,lows(i),'or')
   end
end
hold off