Lecture 8
Algorithms Part II
Outline
• Modularity
• Best Practice
• Examples
Modularity
• How do you solve a big/complex problem?
• Divide it into small tasks and solve each task.
Then combine these solutions.
Divide and Conquer
3
Structure Chart
Shows how the program separated into
tasks and which tasks reference other
tasks.
NOTE: It does NOT indicate the
sequence of steps in the program!
Best Practice
• A module should be dedicated to one task
– Flexibility is provided by input/output parameters
• General purpose modules need
– Description of input/output parameters
– Meaningful error messages so that user
understands the problem
• Organization takes experience
– Goal is not to maximize the number of m-files
– Organization will evolve on complex projects
Example 1 - stat
function [mean, stdev] = stat(x)
% Mean and Standard deviation of an array
% Given the input argument array, this function calculates
% the mean (first output argument) and
% the standard deviation (second argument)
% of the array
% developed by XYZ on April 30, 2014
stat
n=length(x);
mean=sumArray(x)/n;
stdev = sqrt(ssd(x,mean)/n);
end sumArray ssd
Example 1 - sumArray
function s = sumArray(x)
% summation of all array x elements
% Given the input argument array, this function calculates
% the sum of the array elements
s=0;
for i = 1:length(x)
s=s+x(i);
end
end
Example 1 - ssd
function SSD = ssd(x,k)
% Sum of squared difference
% Given the input argument array x and scalar k this function
% calculates the sum of the squared difference between
% each elements of x and k
SSD=0;
for i = 1:length(x)
SSD=SSD+(x(i)-k)^2;
end
end
Example 2 - main
• Read an array from the user and calculates the
sum of non-duplicate items
X=input(‘enter array:’);
Y=removeDuplicate(X);
S=sumArray(Y);
‘ or S=sumArray(removeDuplicate(X));
fprintf(‘Sum of non-duplicates = %d\n,S);
Example 2 - removeDuplicate
function Y = removeDuplicate(X)
% copy non duplicate elements from X to Y
k=1; % index for the array Y
for i=1:length(X)
c=0;
for j=i+1:length(X)
if X(i) == X(j) % compare each element and the next one
c=c+1;
break; % exit inner most loop
end
end
if c==0 % if no duplicate, then store it in Y
Y(k)=X(i);
k=k+1; % increment the index to point to next location in Y
end
end
disp(Y);
function – DisplayTime, DisplayTimeArray
function DisplayTime(h,m)
fprintf(‘%02d:%02d\n’,h,m);
end
>>DisplayTime(5,10);
05:10
function DisplayTimeArray(t)
for i=1:length(t)
fprintf(‘%02d:%02d\n’,t(i,1),t(i,2));
end
end
>>DisplayTimeArray([5 10; 11 30]);
05:10
11:30
Thank You
Course Site:
http://scholar.cu.edu.eg/?q=eldeib/classes/genn004-computers-engineers
Computers for Engineers – GENN004