8. Modules And Functions

 

8.1  Taking a top-down approach to programming by using modules

8.2  Writing and using general-purpose functions

8.3  Getting multiple outputs from functions

8.4  Giving multiple inputs to functions

8.5  Creating subfunctions

8.6  Calling functions properly

8.7  Drawing on previously defined functions versus creating your own

8.8  Practicing modules and functions

 

 

top of page

8.1 Taking a top-down approach to programming by using modules

 

Code 8.1.1:

 

% College_Admissions_04

 

% Assuming that SATs and GPAs are related to IQs,

% this program generates dummy data for SATs, GPAs, 

% Extra- curriculars (EC), and  distance (Dist) from the

% college, giving larger scores to greater  distance from  % the college (for geographical diversity).

% The SATS and GPAs are summed, each of  the  student's

% three new scores (Acad, EC, and Dist) are normed, and

% then the  min required score for admission is gradually % increased until the number  admitted no longer exceeds

% max_admits_allowed.

 

 

% Clear variables, clear and open the commandwindow

clear all

clc

commandwindow

 

% Set constants

applications = 30;

max_admits_allowed = 10;

 

IQmean = 110;

IQsd = 20;

SATQsd = 10;

SATVsd = 10;

ECsd = 10;

GPAsd = 10;

 

Required_Score_Increase = .05;

 

 

% Generate dummy scores to test the program

for a = 1:applications

    IQ(a) = IQmean + abs(randn)*IQsd;

    SATQ(a) = IQ(a) + abs(randn)*SATQsd;

    SATV(a) = IQ(a) + abs(randn)*SATVsd;

    GPA(a) = IQ(a) + abs(randn)*GPAsd;

 

    Acad(a) = SATQ(a) + SATV(a) + GPA(a);

 

    EC(a) = abs(randn)*ECsd;

    Dist(a) = abs(randn);

 end

 

 

% Normalize the scores

Acad = (Acad - min(Acad)) ./ (max(Acad)-min(Acad));

EC = (EC -min(EC)) ./(max(EC)-min(EC));

Dist = (Dist - min(Dist)) ./(max(Dist)-min(Dist));

 

 

% Create a Scores matrix, including, in the final column,

% each student's total score

Scores = [Acad' EC' Dist'];

Total_Scores = sum(Scores');

Scores = [Scores Total_Scores'];

 

 

% Increase min_Required_Score until

% Students_Accepted <= max_admits_allowed

min_Required_Score = min(Scores(:,end));

Students_Accepted = inf;  % To ensure entering while

 

while Students_Accepted > max_admits_allowed

    min_Required_Score = min_Required_Score + Required_Score_Increase;

    Students_Accepted = 0;

    for  a = 1:applications

        Acceptance(a) = 0;

        if Scores(a,end) > min_Required_Score

            Acceptance(a) = 1;

            Students_Accepted =  Students_Accepted + 1;

        end

    end

end

 

% Display the results

disp('Student Number, Academics, EC, Distance, Total Score, Acceptance')

disp(' ')

Scores_And_Acceptances = [Scores Acceptance'];

[r,c] = size(Scores_And_Acceptances);

for i = 1:r

    fprintf('%4d',i)

    fprintf('%6.2f',Scores_And_Acceptances(i,1:end-1))

    fprintf('%4d',Scores_And_Acceptances(i,end))

    fprintf('\r')

end

Students_Accepted

min_Required_Score

 

Output  8.1.1:

 

Student Number, Academics, EC, Distance, Total Score, Acceptance

 

   1  0.53  0.60  0.38  1.51   1

   2  0.26  0.19  0.93  1.38   1

   3  0.65  0.00  0.44  1.08   0

   4  1.00  0.38  0.67  2.05   1

   5  0.17  0.92  0.89  1.98   1

   6  0.35  0.07  0.51  0.93   0

   7  0.02  0.28  0.15  0.44   0

   8  0.35  0.03  0.20  0.57   0

   9  0.52  0.44  0.24  1.20   0

  10  0.33  0.85  0.36  1.54   1

  11  0.29  0.21  0.17  0.67   0

  12  0.54  0.27  0.53  1.33   1

  13  0.15  0.21  0.00  0.36   0

  14  0.14  0.04  0.17  0.35   0

  15  0.21  0.18  0.82  1.21   0

  16  0.18  0.50  0.24  0.92   0

  17  0.22  0.29  0.41  0.92   0

  18  0.06  0.37  0.01  0.44   0

  19  0.19  0.02  0.08  0.29   0

  20  0.37  0.18  0.10  0.65   0

  21  0.26  0.69  0.11  1.06   0

  22  0.79  1.00  0.48  2.27   1

  23  0.15  0.97  0.62  1.74   1

  24  0.26  0.68  0.05  0.99   0

  25  0.25  0.10  0.26  0.62   0

  26  0.00  0.69  0.22  0.91   0

  27  0.21  0.13  0.32  0.66   0

  28  0.66  0.63  0.26  1.55   1

  29  0.34  0.20  1.00  1.54   1

  30  0.42  0.14  0.34  0.91   0

 

Students_Accepted =

 

    10

 

 

min_Required_Score =

 

    1.2392

 

Code 8.12:

 

% College_Admissions_Main.m

 

 

Clear_Start;

Set_Constants;

Generate_Dummy_Scores;

Normalize_Scores;

Create_Scores_Matrix;

Select_Students;

Display_Results;

 

Code 8.1.3:

 

% Clear_Start.m

 

% Called by College_Admissions_Main.m

 

clear all

clc

commandwindow

 

 

Code 8.1.4:

 

% Set_Constants.m

 

% Called by College_Admissions_Main.m

 

applications = 30;

max_admits_allowed = 10;

 

IQmean = 110;

IQsd = 20;

SATQsd = 10;

SATVsd = 10;

ECsd = 10;

GPAsd = 10;

 

Required_Score_Increase = .05;

 

Code 8.1.5:

 

% Generate_Dummy_Scores.m

 

% Called by College_Admissions_Main.m

 

for a = 1:applications

 

    IQ(a) = IQmean + abs(randn)*IQsd;

    SATQ(a) = IQ(a) + abs(randn)*SATQsd;

    SATV(a) = IQ(a) + abs(randn)*SATVsd;

    GPA(a) = IQ(a) + abs(randn)*GPAsd;

 

    Acad(a) = SATQ(a) + SATV(a) + GPA(a);

 

    EC(a) = abs(randn)*ECsd;

    Dist(a) = abs(randn);

 

end

 

 

Code 8.1.6:

 

% Normalize_Scores.m

 

% Called by College_Admissions_Main.m

 

Acad = (Acad - min(Acad)) ./ (max(Acad)-min(Acad));

EC = (EC -min(EC)) ./(max(EC)-min(EC));

Dist = (Dist - min(Dist)) ./(max(Dist)-min(Dist));

 

 

Code 8.1.7:

 

% Create_Scores_Matrix.m

 

% Called by College_Admissions_Main.m

 

% Create a Scores matrix, including, in final column, each student's

% total score

Scores = [Acad' EC' Dist'];

Total_Scores = sum(Scores');

Scores = [Scores Total_Scores'];

 

 

Code 8.1.8:

 

% Select_Students.m

 

% Called by College_Admissions_Main.m

 

% Increase min_Required_Score until

% Students_Accepted <= max_admits_allowed

min_Required_Score = min(Scores(:,end));

Students_Accepted = inf; %To ensure entering while loop

while Students_Accepted > max_admits_allowed

    min_Required_Score = min_Required_Score + ...           
        Required_Score_Increase;

    Students_Accepted = 0;

    for  a = 1:applications

        Acceptance(a) = 0;

        if Scores(a,end) > min_Required_Score

            Acceptance(a) = 1;

            Students_Accepted =  Students_Accepted + 1;

        end

    end

end

 

Code 8.1.9:

 

% Display_Results.m

 

% Called by College_Admissions_Main.m

 

disp('Student Number, Academics, EC, Distance, Total Score, Acceptance')

disp(' ')

Scores_And_Acceptances = [Scores Acceptance'];

[r,c] = size(Scores_And_Acceptances);

for i = 1:r

    fprintf('%4d',i)

    fprintf('%6.2f',Scores_And_Acceptances(i,1:end-1))

    fprintf('%4d',Scores_And_Acceptances(i,end))

    fprintf('\r')

end

Students_Accepted

min_Required_Score

 

 

top of page

8.2 Writing and using general-purpose functions

 

 

Code 8.2.1:

 

 r = [1:99];                

 mean_r = mean(r)               

 

Output 8.2.1:

 

mean_r =

 

    50

 

Code 8.2.2:

 

% normalize.m

 

 function y = normalize(x)                

 y = (x - min(x)) ./ (max(x)-min(x));

 

 

 

Code 8.2.3:

 

 x = [1:11];

 normalized_values = normalize(x)   

 

 

Output 8.2.3:

 

normalized_values =

 

  Columns 1 through 8

 

         0    0.1000    0.2000    0.3000    0.4000    0.5000    0.6000    0.7000

 

  Columns 9 through 11

 

    0.8000    0.9000    1.0000

 

 

Code 8.2.4:

 

 clear normalized_values

 a = [1:11];

 normalized_values = normalize(a)                

 

 

Output 8.2.4:

 

normalized_values =

 

  Columns 1 through 8

 

         0    0.1000    0.2000    0.3000    0.4000    0.5000    0.6000    0.7000

 

  Columns 9 through 11

 

    0.8000    0.9000    1.0000

 

 

Code 8.2.5:

 

 a = [1:11];

 normalize(a);

 y                

 

 

Output 8.2.5:

 

??? Undefined function or variable 'y'.

 

 

top of page

8.3 Getting multiple outputs from functions

 

Code 8.3.1:

 

function [ly, uy] = normalize_split(x);

 

lx = [];

ux = [];

 

for j = 1:length(x)

    if x(j) <= median(x)

        lx = [lx x(j)];

    else

        ux = [ux x(j)];

    end

end

 

uy = (ux - min(ux)) ./ (max(ux)-min(ux));

ly = (lx - min(lx)) ./ (max(lx)-min(lx));

 

 

Code 8.3.2:

 

 a = logspace(20,22,10);

 [lower_normed, upper_normed] = normalize_split(a)                

 

 

Output 8.3.2:

 

lower_normed =

 

         0    0.0991    0.2644    0.5401    1.0000

 

upper_normed =

 

         0    0.0991    0.2644    0.5401    1.0000

 

 

top of page

8.4 Giving multiple inputs to functions

 

 

Code 8.4.1:

 

% normalize_split_two_args.m

 

function [ly, uy] = normalize_split_two_args(x,i);

 

lx = [];

ux = [];

 

if i == 0  % median split

    for j = 1:length(x)

        if x(j) <= median(x)

            lx = [lx x(j)];

        else

            ux = [ux x(j)];

        end

    end

elseif i == 1   % mean split

    for j = 1:length(x)

        if x(j) <= mean(x)

            lx = [lx x(j)];

        else

            ux = [ux x(j)];

        end

    end

else   % error feedback

    disp('An error was made in the call to normalize_split');

end

 

ly = (lx - min(lx)) ./ (max(lx)- min(lx));

uy = (ux - min(ux)) ./ (max(ux)- min(ux));

 

 

Code 8.4.2:

 

a = logspace(20,22,10);

 

[median_based_lower_norm,median_based_upper_norm_mean] = ...

    normalize_split_two_args(a,0)

 

[mean_based_lower_norm,mean_based_upper_norm] = ...

    normalize_split_two_args(a,1)

 

[other_based_lower_norm,other_based_upper_norm_mean] = ...

    normalize_split_two_args(a,3)

 

Output 8.4.2:

 

median_based_lower_norm =

 

         0    0.0991    0.2644    0.5401    1.0000

 

median_based_upper_norm_mean =

 

         0    0.0991    0.2644    0.5401    1.0000

 

mean_based_lower_norm =

 

         0    0.0325    0.0868    0.1773    0.3282    0.5800    1.0000

 

mean_based_upper_norm =

 

         0    0.3748    1.0000

 

An error was made in the call to normalize_split

 

other_based_lower_norm =

 

     []

 

other_based_upper_norm_mean =

 

     []

 

 

top of page

8.5 Creating subfunctions

 

 

Code 8.5.1:

 

function [y,ty] = mean_and_trimmed_mean(x)

 

y = mean(x);

ty = mean(trimmed(x));

 

function yy = trimmed(x)

 

yy = [x(1):x(end-1)];

 

 

 

Code 8.5.2:

 

 x = [1:5];

 [a b] = mean_and_trimmed_mean(x)

 

 

Output 8.5.2:

 

a =

 

     3

 

 

b =

 

    2.5000

 

 

top of page

8.6 Calling functions properly

 

 

Code 8.6.1:

 

mean_and_trimmed_mean(x)

c = mean_and_trimmed_mean(x)

[d e] = mean_and_trimmed_mean(x)

[f g h] = mean_and_trimmed_mean(x)

 

Output 8.6.1:

 

 

ans =

 

     3

 

 

c =

 

     3

 

 

d =

 

     3

 

 

e =

 

    2.5000

 

??? Error using ==> mean_and_trimmed_mean

Too many output arguments.