Review Sheet 3 Rev 4

Embed Size (px)

Citation preview

  • 8/6/2019 Review Sheet 3 Rev 4

    1/14

    1

    1371 Review Test #31. Matrices/Images

    a. Images are just a three dimensional matrix, or three layers of matrices laid on top of one another, sowell lump them together.

    b. Access matrices my saying mat(row,column) (with numbers obviously)c. Ok, so vectors are of size 1xNx1 and we only need one loop. Matrices are RxCx1 and we need two

    loops to go through each row and each column. Images are RxCxD and we need 3 loops: one for

    rows, one for columns, and one for dimensionality (

  • 8/6/2019 Review Sheet 3 Rev 4

    2/14

    2

    i. Also, some of the nice matrix manipulations we know only work on a 1 dimensional matrix (like thetranspose) in order to fix this, you must iterate through the dimensions and look at each layer

    individually this way you are only dealing with a 1-D matrix.

    2. Sounda. Analog vs. Digital

    i. The main difference between the analog and digital in reference to sound is that the analogsignal is a continuous line whereas the digital signal has to be sampled at a specific time

    interval so that the computer can store the information at specific time intervals and not the

    entire sound.

    ii. Even though we are not hearing every part of the sounds, for standard CD quality, there are44100 samples in a second. In a human sensory phenomenon, our brain fills in the gaps of the

    blank sounds and puts it all together as a continuous sound. (Another example of this

    phenomenon is the idea of blinking: every time you blink, it isnt like the lights go out for a

    split second, but instead your brain fills in the blank data with previous information and

    bridges the gap)

    iii. Nyquist Sampling Theorem: Nyquist way back in the day said that if humans can hear afrequency, lets call it f_hum, then the frequency at which we should sample a given soundshould be at least twice that. f_samp >= 2*f_hum. Turns out that the human can hear

    frequencies up to about 22000Hz. Thus the sampling for cds is 44100 where that extra 100 is

    just a buffer of sorts.

    0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2-1

    -0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8

    1Time Domain

    Am

    plitude

    Time (seconds)

    b. Time Domain (Picture of graph Shown Above):i. Fs is known as the sampling frequency at which any given sound is played. Its formal

    definition is the # of samples per second.

    ii. Therefore the inverse of this, 1/Fs, is the numbers of seconds for a given sample, or in otherwords the amount of time between consecutive samples.

    iii. If we already know the time in between samples (1/Fs) and know how many samples we haveby letting N = length(note) , then the total time for the file is given by tmax = N/Fs since ther

    are N different samples all with a dt in between the samples.

    iv. The note vector is the digital interpretation of the sound. These are the y-values of the plotabove and are the actual amplitude of the sound. When we talk about the amplitude of a

    sound, we are talking about the Pressure variations compared to the pressure variation of a

    reference sounds (usually the smallest variation that the human ear can hear);

    Important Functions you need to know for sound:

    [note, Fs, b] = wavread(music.wav) Wavwrite(newNote, Fs, filename.wav) Y = abs(fft(note)) sound(note,Fs)

  • 8/6/2019 Review Sheet 3 Rev 4

    3/14

    3

    v. In the important functions box at the top right of the page, the variable b in [note, Fs, b]corresponds to the number of bits that are used to record the sound. MATLAB can only

    handle 8 or 16 bit sounds.

    vi. Now we have all the elements to plot the sound in the time Domain as the name impliestime will be the independent variable and the time vector is given by:

    timeV = dt:dt:tmax. And since we already know what the corresponding y-values are (note

    vector duh) we can just plot(timeV,note) for a graphical interpretation of the time domain

    of the sound. This is the picture of the above plot.

    1. Note here that the first time at which the first amplitude is sampled is not at time = 0seconds. This should make intuitive sense because if you start recording at a specified

    time, , it will take a time of dt to actually record the first sample.

    c. The power domain is a little different; it deals with plotting the power as a function of frequencies.

    0 0.5 1 1.5 2 2.5 3 3.5 4 4.5

    x 104

    -500

    0

    500

    1000

    1500

    2000

    2500

    3000

    3500

    4000

  • 8/6/2019 Review Sheet 3 Rev 4

    4/14

    4

    iv. Thus now we have the the values to plot this guy. FreqV = df:df:2*fmax. Why must we go to2*fmax you ask. Well, the reason is if we only go to fmax, we will only get the left side of the

    graph.

    1. In the case you only want to plot the left side: plot(df:df:fmax,Y(1:round(end/2)))d. Important ideas/Tricky Information Stuff

    i. FFT has as many samples as note doesii. If you are asked to find out at what index a given frequencies energy level is given, use the

    formula: index = (freq_asked)/df + 1 or index = #of samples (freq_asked)/df

    iii. If you are asked to find at what frequency the maximum energy level occurs, use the maxfunction on the Y vector of fft values to get out the max value AND the location. Once you

    have that location, use it to index freqV and you have the location.

    1. [ maxV , loc ] = max(Y);freqOfMaxEnergy = freqV(loc)

    iv. The nice thing about sounds is that note is just a vector of amplitudes and you are allowed todo whatever you wish to that vector. You can stretch it to make the sound play out longer

    and slower of shrink it so that the sound is faster. You can also multiply all the amplitudes by

    a given factor, or perhaps most importantly change the pitch at which a sound is played.1. You may want to think about how doubling the number of samples in ta note vector

    will have a similar effect as decreasing Fs by a factor of 2 why is that?

    v. In the event that you only want to play a sound for a given amount of time, , then youshould multiply it and Fs to determine the number of samples to play:

    1. sound(note(1:Fs* ) , Fs)vi. We normally have dealt with raising a note by a half note. To do this, we can initialize: half =

    2^(1/12). From here to raise it a half note, we play select frequencies of the main source file.

    So given: [note, Fs, b] = wavread(music.wav), to play the note at X half notes higher:

    1. factor = half.^XnewL = ceil(N/factor);

    index = ciel(linspace(1,N,newL))

    newNote = note(index)

    3. Numerical Methods I like to think of this as the Big take away from the class in that you are applying allpreviously

    learned techniques and ideas to a real-world applicable situation.

    Numerical Methods is the study of algorithms for discrete and continuous mathematics. There are 5general ideas that we concentrate on in this class: Interpolation, Curve Fitting, Numerical

    Integration, Numerical Differentiation, and Root finding (although on verybriefly).

  • 8/6/2019 Review Sheet 3 Rev 4

    5/14

    5

    a. Curve Fitting / Interpolation (look at CurveFitAndInterp.m for code to produce plot below)

    5 10 15 20

    4

    6

    8

    10

    12

    14

    16

    18

    20

    Data Points

    Linear Interpolation

    Spline Interpolation

    1st Order Polyfit

    2nd Order Polyfit3rd Order Polyfit

    4th Order Polyfit

    i. The fundamental difference between curve fitting and Interpolation is the idea of local versusglobal approximations.

    1. Interpolation uses a local guess by checking data points that are close to your test datapoint and interpolates to find an answer. Interp1 uses a linear interpolation model

    whereas the spline function uses a cubic interpolation model. ** the interp1 function

    can have a 4thparameter: linear, nearest, spline, pchip, cubic, v5cubic . Make

    sure you look in the book on these parameters and know what each does.

    2. Curve fitting looks at the data group as a whole and tries to fit a polynomial that bestrepresents the data. It does so by using the function where it is

    looking to minimize the sum of the squared errors. Instead of looking at the

    neighboring points only, curve fitting looks at the total trend of the data set.3. The issue comes in which areas will you want to use one over the other.

    Interpolation is nice in that an interpolation model will always go though all the

    different data points in the set whereas in Curve fitting, only if you have N+1 data

    points and an Nth order polynomial will the curve go through all the points. Most of

    the time for experimental data, you have flawed data and thus interpolation is not a

    very good model. Choosing which to use comes with experience, and later classes.

    Make sure you can have a small discussion on how these two methods differ from

    each other.

    ii. Interpolation: given an X value that lies within the range of a given x and y vector of data,linear interpolation will create a line between the two nearest points, and evaluate the test Xvalue on the equation of the line. **note, the x and y data set much be inputted so that the x

    values are in ascending order. Recalling the equation of a line in point slope form:

    , we can write a function that does the same as interp1. For

    simplicity, we will write the function just for a scalar newX value.

    Important Functions for Curve Fitting and

    interpolation:

    coeffs = polyfit(x,y,order) yVals = polycal(coeffs,newXs) yInterpL = interp1(x,y,newXs) yInterpS = spline(x,y,newXs)

    ** newXs can be a scalar or a vector

  • 8/6/2019 Review Sheet 3 Rev 4

    6/14

    6

    iii. Curve fitting uses the data points for a Trend lines. It is important to know that if you want tofit an Nth order polynomial to a set of data points, you MUST have at least N+1 data points

    (think about trying to fit a line to just one point there are infinitely many solutions to that

    problem). The polyfit function is slightly advanced problem and I will leave it to the

    problems at the end of this sheet to help you through writing that. Assuming we have the

    actual coefficients, it then becomes important to evaluate that polynomial fit at an X value.

    Thinking about the coeffs vector, if it has 4 elements in it, that means that there is a

    polynomial in the form of: therefore the vector of

    exponents is related to the length of coeffs: exps=length(coeffs)-1:-1:0

    b. Numerical Differentiationi. Numerical integration is often very useful to engineers because it is not often that an

    analytical solution comes our way. We have to learn how to take a given data set and

    optimize it. And as your Calc classes have taught you, optimization starts with the derivative

    The derivative of a function is defined as , or in more crude terms, the

    derivative is the change in the function values over a differential distance. Since MATLAB

    function ret = myInterp(x,y,newX)%% This function uses Linear Interpolation to interpolate the value of newX%% in the data set provided in x and y% Check to make sure that newX is in the given data Rangeif newX < x(1) | newX>x(end)

    ret = error('Cannot Extrapolate Data');% Checks to see if the Data Values are Sorted

    elseif x~=sort(x)

    ret = error('Data Values not Sorted')else

    looking = true; %Find where x value lies betweenindex = 1; % Initializes the indexwhile looking

    % checks to see if newX lies in between consecutive valuesif newX > x(index) & newX < x(index+1)

    slope = (y(index+1)-y(index))/(x(index+1)-x(index));ret = slope*(newX - x(index))+y(index); % Point Slope Formulalooking = false; % Stops looking

    elseindex = index+1; % increases Index

    endend

    end

    function ret = myPolyVal(coeff,newX)% Initialize the tmp vector to hold all the polynomial valuestmp = [];for index = 1:length(coeff)

    exp = length(coeff)-index; % created the exponenttmp(index) = coeff(index).*(newX.^(exp)); % uses polynomial form

    endret = sum(tmp); % sums up the Polynomial Vecor

    %% Alternatively% function ret = myPolyVal(coeff,newX)

    % exps = length(coeff)-1:-1:0;% ret = sum(coeff.*newX.^exps);

  • 8/6/2019 Review Sheet 3 Rev 4

    7/14

    7

    and any given data set will limit it to a step size that is not infinitesimal, we will only get a

    good approximation (the level of good depends on how closely spaced the points are)

    ii. To make life nice and convenient, MATLAB has the built-in diff() function that will take in avector and compute the difference between the (i+1)th term and the ith term. For example, i

    vec = [ 4 9 12 22 28 37] then diff(vec) will return [5, 3, 10, 6, 9]. A subtle note here is that the

    length(diff(vec)) is one less than the length(vec). Following the forward-difference method,

    we will just start the x values for the derivative from the 2 original x value to the end. The

    backwards difference method will start at the original x value and go to the second-to-last

    value.

    0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 50

    10

    20

    30

    40

    50

    60

    70

    80

    Function

    Forward Diff dy/dx

    Backward Diff dy/dx

    iii. Make sure that if we as mean people decide not to let you use the diff function that you canstill do derivative work

    c. Root Findingi. Even though we only briefly touched on this class, you are still responsible for the aspects of

    root finding. The fundamental idea is fairly simple: look through the function values and see

    when the sign changes: if either a positive value is followed by a negative value or a negative

    value is followed by a positive value, then it is understood that somewhere in between them,

    the function crosses the axis by the Intermediate Value Theorem.

    ii. Note that it is very easy to solve for the intersection of two functions: f(x) = g(x) by simplysubtracting g(x) from both sides and solving for the root of the function f(x)-g(x) = 0

    x = linspace(0,5,100);y = x.^3-3*x.^2+6*x;

    dydx = diff(y)./diff(x);xForDiff = x(2:end);xBackDiff = x(1:end-1);

    plot(x,y,'k',xForDiff,dydx,'r',.

    ..xBackDiff,dydx,'g')

    legend('Function','Forward Diff

    dy/dx'...,'Backward Diff dy/dx',...'Location','NorthWest')

    From Deriv.m

  • 8/6/2019 Review Sheet 3 Rev 4

    8/14

    8

    0 1 2 3 4 5 6 7-1

    -0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8

    1cos(x) with roots

    d. Derivatives + Root Finding = Critical Values:

    i. If you combine these two ideas, you will be left with a very powerful function. Below is thesource code and the output of a test case: Make sure you can follow the code. There is a lot of

    extra stuff going on in the code, but the idea of critical values is not to complex for us to

    ask writing the derivative is very easy and the code for root finding is almost as short So

    just use the two functions in conjunction with each other and you have it!

    0 1 2 3 4 5 6

    -1

    -0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8

    1

    Function

    Derivative

    e. Numerical Integrationi. Numerical Integration is one of the more important tasks that we have in this class. The idea

    of the integral is very powerful and is used very often. Again, it is not often that we have

    continuous function to deal with and we often have to integrate a discrete function. There are

    several methods to do this for us: left hand endpoint, right hand endpoint, midpoint,

    trapezoid and Simpsons.

    1. With the exception of Simpsons rule, all of the other methods can be done with non-constant spacing in the x values. Simpsons requires evenly spaced x value as well as

    x = linspace(0,2*pi,1000);y = cos(x);y1 = y(1:end-1);y2 = y(2:end);tempV = y1.*y2;locs = find(tempV

  • 8/6/2019 Review Sheet 3 Rev 4

    9/14

    9

    an even amount of intervals to integrate over. An even amount of segments means

    that there must be an odd number of data points by the telephone pole postulate

    2. If you look at the numInt.m file provided with this sheet, you will see the code foreach of the techniques. The script will print out the results of each of the techniques

    and there is a plot that shows how each technique is coming up with the answers.

    You should be very proficient and writing any one of the techniques, so make sure to

    do #1 on the review problems at the bottom of the sheet.

    ii. For integrating over a section from ato bwith n segments: (n segments means n+1 points)1. Left Hand Endpoint Formula:2. Right Hand Endpoint Formula:3. Midpoint Formula:4. Trapezoidal Formula:

    a. ** note that the trapezoidal format has many different forms, but they will allcome out to the same answer Make sure you look at all the forms you have

    seen thus far and can implement them.

    5. Simpsons Rule:

    a. Simpsons Rule is probably the hardest and messiest. It is easiest to approachthe problem by solving it with a series of vector operations.

    f. Plotting Integrals and Derivativesi. Look at the homework problem that had you plot the integral (derived from the trapezoidal

    rule) and make sure you understand the process of the problem.

    0 0.5 1 1.5 2 2.5 3-5

    0

    5

    10

    15

    20

    25

    Function

    Numerical Derivative

    Actual Derivative

    Numerical Integral

    Actual Derivative

    ii. Here is an important idea that you should remember: If I were to take the derivative of the

    integral, I am left with the original function (fundamental Theroem of calculus) missing

    the first x value. So if were to compare the derivative of the integral to the original function

    values from 2 to the end should they be the same?

    This is the result of

    running the plotInt.m file.As you can see, it plots

    the original function as

    well as both thenumerical and analytical

    functions for the

    derivative and integral. Ifyou look at the code and

    increase the number of

    points used in the

    numerical solutions, you

    will see theapproximations become

    closer and closer to the

    actual solution. TheIntegrals are already very

    close

  • 8/6/2019 Review Sheet 3 Rev 4

    10/14

  • 8/6/2019 Review Sheet 3 Rev 4

    11/14

    11

    i. What bubble sort does is it will look at two numbers next to each other and swap the twonumbers if the number on the right is greater than the number on the left. This bubble is

    only looking at two elements at a time and will go through the vector at most n^2 times.

    ii. The bubble will start at the far left and look at the first 2 elements, then will perform a aswapif necessary and then will look at the 2nd and 3rd elements and so on until it gets to the end of

    the vector. After the bubble has made it to the last two elements of the vector, we say that it

    has made one pass through the vector.

    iii. The bubble will make up to N passes through the vector, but you can stop once the vector issorted.

    g. **A good thought would be to go through the book and look over the coding of these algorithms sohat you would be able to identify what some coding would do if we gave it to you on a test.

    As always, if you have any questions or comments, please let me know.

    Michael Wondrasek

    [email protected]

    gtjackets13

    Good Luck!!

    mailto:[email protected]:[email protected]:[email protected]
  • 8/6/2019 Review Sheet 3 Rev 4

    12/14

    12

    Sample Questions:1. Go ahead and write the following functions that incorporate the Numerical Methods Mentioned Above. All

    of the functions will take in two vectors: one containing the x-values, the other containing the y-values. You

    may not assume that there is a constant spacing between x-values except when writing Simspons.

    a. leftHandSumb. rightHandSumc. midpointSumd. trapezoidalSume. simpsonsSum (Check for value inputs!)

    2. Write a function called findaRoot.m that again takes in two vectors, on containing x-values, the other y-values. This time, your output should be a string saying the two x-values which the root lies between (use

    your knowledge of sprintf() that you learned from OO ). You are free to assume that only one root will lie in

    the given vectors.

    a. Hint: what do you know about the product of two y values that surround a root?? The functionshould work in the case of multiple roots existing in the given data set.

    b. Below is an Example of how the program should be run and how the output should look:

    3. Write a function called myDeriv.m that takes in two vectors, on containing x-values, the other y-values.Now you want to compute the numerical derivative. The best way that this can be done is by implementing

    the diff() function. Now, there is a trick to this Look Below:

    As you can see, the length of the vector after using the diff() function is one less than the original vector.

    To take care, of the problem with diff(), just use newX = x(2:end) This is a bit of a simplification of the

    problem, but it matters that you know what to do. The last thing I want your function to do is graph boththe original vectors and newX and newY on the same graph so that you can see that it does truly compute ou

    the derivative.

    4. So the next function is a lot more fun. This time you want to create a function called myPolyFit.m that willagain take in two vectors, on containing x-values, the other y-values, but will also take in a number which

    will correspond to the order of the polynomial of which you want to fit the data. Now, the way curve fitting

    works is by setting up a large system of equations like shown. Given that we are fitting the data to an nth

    order polynomial for any x value, the general form of the polynomial is:

    >> x = linspace(0,pi,1000);>> y = cos(x);

    >> findaRoot(x,y)

    ans =The root lies between 1.569224e+000 and 1.572369e+000

    >>

    function root = findaRoot(x,y)

    >> a = [ 2 3 5 6 8 9 11 12]

    a =2 3 5 6 8 9 11 12

    >> diff(a)

    ans =1 2 1 2 1 2 1

    function [newX, newY] = myDeriv(x,y)

  • 8/6/2019 Review Sheet 3 Rev 4

    13/14

    13

    We get the following Matrices for an Nth order polynomial with M data points where M +1>=N :

    Now, if, we look at this like * X A Y , we can create the X and Y matrices using iteration and

    MATLAB is nice enough to provide us with its back divide method. As many of you remember, MATLAB

    will allow you to do \ A X Y to solve a system of equations. Luckily this is also the least squares

    solution to the problem. Now, for the output of your function I want you output to be a row vector

    containing the values of A. When you solve in MATLAB, it will give you a column vector, so just take the

    transpose and youll be ok. I know this problem may be a little intimidating, but I swear the coding isnt that

    bad!! (its actually only 7 lines of code!!) (P.S. You are actually re-writing the MATLAB function polyfit).

    5. Given the Vector, vec = [2 7 4 3 6 5 1], do all the sorting algorithms you learned in class.6. Here is a code that I wrote

    I want you to explain what

    is going on Yes I

    know that this is beyond

    ugly, it is supposed to be, and

    it is great practice. There are some

    lines that I commented out that

    just print out what the current

    values are if you are having

    trouble tracing this, cut and paste

    it into MATLAB and take the semi-

    colon off of like 23 so that you

    can follow its progression.7. Youre just having a bad day and

    those same people that sent you that

    crazy messed up picture just send you

    a sound file and its all kind of messed

    up. The first fifth of the song needs

    to be raised 4 half tones, the middle

    three fifths of the song need to be

    amplified in the following manner: squared if they are at an odd index location in the sound vector or square

    rooted if they have an even. The last fifth of the file is actually correct. Now, each fifth of the file is in the

    wrong place and needs to be placed in the correct order so that you can accurately hear what it is trying to

    say. The first fifth of the file is the last part of the song, the second fifth is the second to last part of the song,

    the middle fifth stays the same, the fourth fifth is the first part of the song and lastly the fifth part of the file

    is the second part of the song. Please write this to a fixedWAV.wav file when you have completed all the

    actions

    8. Create a function called plotDervInt that will consume a vector of coefficients of a polynomial curve fit.Your function should proceed to plot the function in blue, the integral in red and the derivative in black all

    over the interval from -5 to 5 with 1000 points. Your function should also output the coefficients of the

    derivative and the integral, respectively

    9. Write a function that reads takes in the filename of .wav file and a frequency. Your function should displayboth the time domain and the frequency domain in the same plot (use the subplot function). Also, your

    function ret = myfunction(vec)ret = myHelper(vec,[]);

    function ret1= myHelper(vec,stuff)if length(vec) == 1

    ret1 = [stuff vec];else

    %vec%stuffyay = inf;for in = 1:length(vec)

    if vec(in)

  • 8/6/2019 Review Sheet 3 Rev 4

    14/14

    14

    function should output three things: the maximum energy in the sound, the frequency at which it occurs,

    and lastly it should output a vector of the two indices where the energy for the input frequency is shown.

    10.Images: you are to create a function that takes in a filename of an existing jpg image. The function shouldmake a PURELYred X on both the main diagonal and the off diagonal to cross it out. No, the diag() function

    will not help you at all. You should write this to a new image file, with is the same as the original file name,

    but with a NO appended to the beginning of it. After you have done this, your function should also output

    the averageand the max intensity present in the image matrix

    11.4. You are given an excel sheet in which the first column contains operators, and the right column obtainsnumbers You are to start at the top right and go through the excel sheet reading left to right top to bottom

    and doing the operations. For example, one of the excel sheets could contain the values:

    { , 6

    + , 7

    * , 3

    - , 15

    / , 8

    ^ , 4 }

    Should go as follows: 6 plus 7 is 13. 13 times 3 is 39. 39 minus 15 is 24. 24 divided by 8 is 3. 3 to the fourth is

    243.

    Write a function that will take in the name of an excel sheet that contains this data and code it to do all the

    work for you Note, the operations may or may not be in the same order as this, so you cannot hard code it

    for this example.

    **Hint: switch/case might be useful here

    12.Write a script that reads in a sounds called mocktest.wav and identifies the following characteristics:a) number of samples

    b) time of the entire sound

    c) lowest frequency MATLAB can detect

    d) highest Frequency it can dectect

    e) the highest amplitude of vibration (positive of negative)

    ** Just some things you may want to be able to do with sound:

    a) play the sound at twice or half the speedb) raise the note by a half tone, or by p half tonesc) plot both the time and frequency domains