Download Outline Arrays Definition and Initialization Function Arguments

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

History of the function concept wikipedia , lookup

Law of large numbers wikipedia , lookup

Elementary mathematics wikipedia , lookup

Transcript
Outline
Arrays
Arrays
Statistical Measurements
Functions Revisited
ELEC 206
Computer Applications for
Electrical Engineers
Dr. Ron Hayne
206_C6
Arrays
Definition and Initialization
Declaration
double x[4];
One-dimensional array
Initialization
double x[4] = {1.2, -2.4, 0.8, 6.1};
int t[100] = {0};
char v[] = {'a', 'e', 'i', 'o', 'u'};
The size of the array must be specified by a constant in brackets, or
by an initialization list
Loops
double g[21];
for (int k=0; k<=20; k++)
{
g[k] = k*0.5;
}
List of values
Arranged in either a row or a column
Offsets (Subscripts) distinguish between
elements in the array
Identifier holds address of first element
Offsets always start at 0
206_C6
3
206_C6
4
Function Arguments
Adding Two Arrays
/*
/* This program adds 2 arrays
2
*/
*/
Passing array information to a function
#include <iostream>
using namespace std;
int main()
{
// Declare and initialize objects.
int x[]={1,3,6,4,6};
int y[]={2,4,1,5,0};
Two parameters usually used
for (int k=0; k<=4; k++)
{
y[k] = x[k] + y[k];
cout << y[k] << endl;
}
Specific array
Number of elements in the array
Always call by reference
Address of the array
system("PAUSE");
return 0;
}
/*----------------------------------------------------*/
206_C6
ELEC 330
5
206_C6
6
1
Data Files
/*
/*
/*
/*
/*
Reading data into arrays
double time[10], motion[10];
ifstream sensor3("sensor3.dat");
...
if(!sensor3.fail())
{
for (int k=0; k<=9; k++)
{
sensor3 >> time[k] >> motion[k];
}
}
206_C6
else
{
// Read a data value from the file.
int N, npts(0);
sensor1 >> N;
double time, y[N];
while (npts <= (N-1))
{
sensor1 >> time >> y[npts];
cout << y[npts] <<endl;
npts++;
// Define constants and declare function prototypes.
double maxval(double x[], int n);
int main()
{
// open file
ifstream sensor1; // Declare object stream
sensor1.open("SENSOR1.DAT");
if(sensor1.fail())
{
cout << "Error opening input file\n";
}
7
206_C6
//read in num pts from file
// declare array y
double maxval(double x[], int n)
{
// Declare local objects.
double max_x;
//read data into y in a loop
// Determine maximum value in the array.
max_x = x[0];
for (int k=1; k<=n-1; k++)
{
if (x[k] > max_x)
max_x = x[k];
}
//print y values to screen
// Increment npts.
// Return maximum value. /
return max_x;
}
/*----------------------------------------------------*/
206_C6
9
206_C6
Statistical Measurements
10
Mean
double mean(double x[], int n)
{
double sum(0);
Maximum
Minimum
Mean (average)
Median (middle)
Variance
for (int k=0; k<=n-1; k++)
{
sum += x[k];
}
Average squared deviation from the mean
Standard Deviation
8
/*----------------------------------------------------*/
/* This function returns the maximum
*/
/* value in the array x with n elements.
*/
// Close file and exit program.
sensor1.close();
}
system("pause");
return 0;
}
*/
*/
This program reads values from a data file and */
calls a function to determine the maximum value */
with a function.
*/
#include <iostream>
#include <fstream>
using namespace std;
}
// Find and print the maximum value.
cout << "Maximum value: " << maxval(y,npts) << endl; //call function maxval()
Program chapter6_2
Square root of the variance
return sum/n;
}
206_C6
ELEC 330
11
206_C6
12
2
Variance
Random Numbers
double variance(double x[], int n)
{
double sum(0), mu;
The following relation exists between the limits
(a, b) of a sequence of uniform random numbers
And the theoretical mean (µ) and variance (σ2).
mu = mean(x,n);
for (int k=0; k<=n-1; k++)
{
sum += (x[k] - mu)*(x[k] - mu);
}
return sum/(n-1);
σ2 =
a=µ−
Problem chapter6_20
12σ 2
2
13
( a + b)
2
and b = 2 µ − a
206_C6
14
HW 6-20 continued
HW Problem 6-20
/*
/*
/*
/*
/*
/*
µ=
Solving for a and b yields
}
206_C6
(b − a ) 2
12
//Define function prototypes
double rand_float(double, double);
double variance(double x[], int);
double mean(double x[], int);
*/
*/
This program generates two sequences of 500 points. Each
*/
sequence should have a theoretical mean of 4, but one sequence */
should have a variance of 0.5 and the other a variance of 2.
*/
The computed means and variances are printed.
*/
int main()
{
/* Define variables and function prototypes. */
int index = 0;
double first_sequence[MAX_POINTS], second_sequence[MAX_POINTS];
double a1, b1, a2, b2, mean1, mean2, var1, var2;
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
/* Find the limits (a1, b1, a2, b2) on the random number generator. */
a1 =
b1 =
a2 =
b2 =
const double MEAN = 4.0;
const double VAR1 = 0.5;
const double VAR2 = 2.0;
const int MAX_POINTS = 500;
206_C6
15
206_C6
HW 6-20 continued
16
Function Overloading
/* Generate random numbers in the sample. */
for (index=0; index<MAX_POINTS; index++)
{
first_sequence[index] =
second_sequence[index] =
}
/* Calculate sample means and variances. */
var1 =
var2 =
mean1 =
mean2 =
Function name can have more than one definition
/* Print results. */
cout << "Sequence 1: Mean: " << mean1 << " Variance: " << var1 << endl;
cout << "Sequence 2: Mean: " << mean2 << " Variance: " << var2 << endl;
cout << "Theoretically: Mean: " << MEAN << " Variance 1: " << VAR1
<< " Variance 2: " << VAR2 << endl;
Each function definition has a unique function signature
Each function call looks for a function prototype with a
matching function signature
double maxval(double x[], int n);
int maxval(int x[], int n);
char maxval(char x[], int n);
system (“pause”);
return (0);
}
/* --------------------------------------------------------*/
// Add the three functions here. 1. rand_float(); 2. variance(); 3. and mean();
206_C6
ELEC 330
17
206_C6
18
3
Function Templates
Sorting Algorithms
Generic algorithm for a function that is not tied to a
specific data type
Sorting
template <class Data_type>
Data_type minval(Data_type x[], int n)
{
Data_type minx;
...
206_C6
Arranging in ascending (descending) order
Not one "best" algorithm
Selection Sort
Depends on characteristics of data
Find smallest value from current position to end
Swap smallest with current position
Move to next position
19
//Chap6_selection_sort.cpp
#include <iostream>
#include <cstdlib>
using namespace std;
206_C6
20
void sort(double x[], int n) // Selection sort
{
int m; // marker
double hold;
void sort(double x[], int n);
void display(double x[], int n);
const int N = 6;
for (int k=0; k<=n-2; k++)
{
m = k; // Find smallest value
for (int j=k+1; j<=n-1; j++)
{
if (x[j] < x[m])
m = j;
}
hold = x[m]; // Swap smallest with current
x[m] = x[k];
x[k] = hold;
cout << "After k=" << k << endl;
display(x, n);
}
int main()
{
double data[N] = {5.0, 3.0, 12.0, 8.0, 1.0, 9.0};
cout << "Initial data" << endl;
display(data, N);
sort(data, N);
cout << "Sorted data" << endl;
display(data, N);
}
Problem Solving Applied
void display(double x[], int n)
{
for (int k=0; k<=n-1; k++)
{
cout << x[k] << ' ';
}
cout << endl;
}
Speech Signal Analysis
Problem Statement
Compute the following statistical measurements for a
speech utterance: average power, average magnitude,
and number of zero crossings.
Input/Output Description
Average power
Average magnitude
Zero crossings
Zero.dat
206_C6
ELEC 330
23
206_C6
24
4
Problem Solving Applied
Problem Solving Applied
Hand Example
test.dat
2.5 8.2
Algorithm Development
-1.1
-0.2
1.5
main
read speech signal from data file and determine number of
points, n
Average power = 15.398
Average magnitude = 2.7
Number of zero crossings = 2
compute statistical measurements using functions
ave_power(x, n)
set sum to zero
for k: add x[k]2 to sum
return sum/n
206_C6
25
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
Algorithm Development
26
/*---------------------------------------------------*/
/* This program computes a set of statistical
*/
/* measurements from a speech signal.
*/
Problem Solving Applied
206_C6
ave_mag(x, n)
set sum to zero
for k: add |x[k]| to sum
return sum/n
// Declare function prototypes and define constants.
double ave_power(double x[], int n);
double ave_magn(double x[], int n);
int crossings(double x[], int n);
crossings(x, n)
set count to zero
for k: if x[k] * x[k+1] < 0, increment count
return count
const int MAXIMUM = 2500;
206_C6
27
int main()
{
// Declare objects.
int npts=0;
double speech[MAXIMUM];
string filename;
ifstream file_1;
// Read information from a data file.
while (npts <= MAXIMUM-1 && file_1 >> speech[npts])
{
npts++;
}
// Compute and print statistics.
cout << "Statistics \n";
cout << "\taverage power: " << ave_power(speech,npts)
<< endl;
cout << "\taverage magnitude: "
<< ave_magn(speech,npts) << endl;
cout << "\tzero crossings: " << crossings(speech,npts)
<< endl;
// Prompt user for file name and open file.
cout << "Enter filename ";
cin >> filename;
file_1.open(filename.c_str());
if( file_1.fail() )
{
cout << "error opening file " << filename
<< endl;
return 1;
}
// Close file and exit program.
file_1.close();
system("PAUSE");
return 0;
}
ELEC 330
5
/*---------------------------------------------------*/
/* This function returns the average power
*/
/* of an array x with n elements.
*/
/*---------------------------------------------------*/
/* This function returns the average magnitude
*/
/* of an array x with n values.
*/
double ave_power(double x[], int n)
{
// Declare and initialize objects.
double sum=0;
double ave_magn(double x[], int n)
{
// Declare and initialize objects.
double sum=0;
// Determine average power.
for (int k=0; k<=n-1; k++)
{
sum += x[k]*x[k];
}
// Determine average magnitude.
for (int k=0; k<=n-1; k++)
{
sum += abs(x[k]);
}
// Return average power.
return sum/n;
// Return average magnitude.
return sum/n;
}
}
/*---------------------------------------------------*/
/* This function returns a count of the number
*/
/* of zero crossings in an array x with n values.
*/
Testing
int crossings(double x[], int n)
{
// Declare and initialize objects.
int count=0;
// Determine number of zero crossings.
for (int k=0; k<=n-2; k++)
{
if (x[k]*x[k+1] < 0)
count++;
}
// Return number of zero crossings.
return count;
}
/*---------------------------------------------------*/
206_C6
Testing
Summary
Arrays
Statistical Measurements
Functions Revisited
Problem Solving Applied
Selection Sort
End of Chapter Summary
206_C6
ELEC 330
34
35
C++ Statements
Style Notes
Debugging Notes
206_C6
36
6