Problem 4 – Coding Problems [40 Points] Function name: timeCount Inputs: (2) 1. amount of hours (double) 2. amount of minutes (double) Outputs: (2) 1. total number of seconds (double) 2. percentage of one day (double) Write a function named timeCount which takes in a number of hours and a number of minutes and gives back the total number of seconds and what percentage of the day it is. Test Case: [sec percent] = timeCount(12,30) sec--> 45000 percent--> 52.0833 Solution: function [seconds, percent] = time(hours, minutes) minute_seconds = minutes .* 60; hour_seconds = hours .* 60 .* 60; seconds = hour_seconds + minute_seconds; day = 24 .* 60 .* 60; percent = (seconds ./ day) .* 100; end Problem: Function Name: SortRotate Inputs (1): (double)- a row vector of numbers Outputs (1): (double)- the input vector with any number greater than 20 removed, then sorted, then the vector mirrors itself. Function Description: Given a vector of numbers, write a function "SortRotate" which will eliminate any number in the vector greater than 20. The function will then sort the remaining numbers, and create a mirror image of itself. Test Case: out= SortRotate([1 50 22 3 -5 0 40 2]) out -> [-5 0 1 2 3 3 2 1 0 -5] Solution: function out = SortRotate(vector) a= vector<20; b=vector(a); sort_b= sort(b); c= sort_b(end:-1:1); out= [sort_b c]; end Problem: Inputs (2): (double)- first row vector (double)- second row vector Outputs (1): (double)- an intertwined row vector Function description: Write a function VecMix, which will intertwine two input vectors. That is, the first element in the first vector input vector is the first element in the new vector. The first element in the second input vector is the second element in the new vector. The second element in the first vector is the third element in the new vector and so on. If one vector is longer than the other, put 0's as place holders. Test Case: out = VecMix([2 5 4], [7 6 0 1 3]) out -> [2 7 5 6 4 0 0 1 0 3] Solution: function out = VecMix(arr1, arr2) total= [arr1 arr2]; length_total= length(total); out= zeros(1,length_total); c=length(arr1).*2; d=length(arr2).*2; out(1:2:c)=arr1(1:1:end); out(2:2:d)=arr2(1:1:end); end Problem: Function Name: oddsAndEvens Input (1) : a row vector Output (1): a row vector contain the following values: 1. the total number of odd numbers 2. the total number of even numbers 3. the total number in the row vector Function Description: Write a function that will take in a vector as its input and then it will return a vector whose 1st element will the total number of odd values (NOT POSITIONS) , the 2nd element will be the total number of even values (AGAIN NOT POSITIONS), and for the 3rd and final element , the total number of elements in that vector. The output vector again should have a total of 3 elements. Hint: try adding true + true in MATLAB. Test Case: out = oddsAndEvens([4 9 10 32 14 7]) out --> [2, 4, 6] Solution: function newVec = oddsAndEvens(vec) odds = sum(mod(vec,2)==1); evens = sum(mod(vec,2)==0); total = length(vec); newVec = [ odds evens total]; end Problem: Function Name: range5and10 Input (1): a row vector Outputs(2): - a modified version of the input row vector with numbers between 5 and 10 removed (inclusive) - a modified version of the input row vector with numbers not between 5 and 10 removed(exclusive) Function Description: Write a function that will take in a vector and will first output a row vector with numbers between 5 and 10 inclusive removed from the original vector. (Inclusive means you include the numbers 5 and 10). The second output should be a vector that remove all the numbers inside the original vector that are not in the interval 5 to 10 (exclusive). (Exclusive means you do not include the numbers 5 and 10). Test Case: [out1 out2] = range5and10([6 10 3 14 9 5 7 0]) out1 --> [3 14 0] out2 --> [6 10 9 5 7] Solution: function [out1 out2] = range5and10(vec) out1 = vec(vec >= 5 & vec <= 10); out2 = vec(vec < 5 | vec > 10); end Problem: Function Name: sumArr() Input (1): an array Output (1): the same array concatenated with sums for its columns and rows and the total sum like so: arr is the input arr = 1 7 0 output 1 7 0 8 2 2 8 = 2 2 8 12 8 6 1 8 6 1 15 11 15 9 35 Function Description: Write function that will take in an array. The output array should be such that the bottom row of is the sum of all the columns in the inputted array and the leftmost column is the sum of all the rows. The leftmost number on the bottom row should be the sum of all the elements in the array. Solution: function newArr = sumArr(arr) newArr = [arr; sum(arr)]; newArr = [newArr sum(newArr,2)]; end Problem: Function Description: Write function that takes in an array and sorts the values in successive columns. When the modified array is given as an output, it has to have the same dimensions are the original array inputted. Hint: the reshape() function may be useful Function Name: sortArr() Input (1): an array Output (1): sort an array column-wise in this manner: arr is the input arr = 1 7 0 2 2 8 8 6 1 0 1 1 2 2 6 7 8 8 out = Solution: function newArr= sortArr(arr) [ r c] = size(arr); temp = sort(arr(:)); newArr = reshape(temp,r,c); end Problem: Function Name: ArrayMod() Input (1): (double)- an array Output (1): (double)- the modified array Function Description: Write a function ArrayMod which takes in an array and performs the following opperations on it: 1 - remove all the even columns. 2 - switch the first and last rows. 3 - divide each odd number by 4. Test Case; out = ArrayMod([3 4 1; -1 9 2; 6 7 8]) out -> [6 8; -0.25 2; 0.75 0.25] Solution: function modified = ArrayMod(arr) modified= arr; modified(:, 2:2:end) = []; first_row= modified(1,:); last_row= modified(end, :); modified(1,:)= last_row; modified(end,:)= first_row; modified(mod(modified,2)==1) = modified(mod(modified,2)==1) ./4; end Problem: Function Name: LetterCmp() Inputs (2): (char)- a string (char)- another string Output (1): (char)- the letters which appear in the same spot for both strings Function Description: Write a function LetterCmp which takes in two strings. The function returns the letters which are in the same spot (index) for both strings. It is case sensative. You may assume the longer of the two words will always be the first input. Test Case: out= LetterCmp('Georgia Tech', 'Storage') out = 'or' Solution: function out = LetterCmp(str1, str2) str1= str1(str1>='a' & str1 <= 'z' | str1>='A' & str1<='Z'); str2= str2(str2>='a' & str2 <= 'z' | str2>='A' & str2<='Z'); positions= find(str1(1:length(str2))==str2); out= str1(positions); end Problem: Function Name: Compare() Inputs (2): (char)- a string (doulbe)- a vector Output (1): (char)- the relationship between the string and vector Function Description: You are given a string and a vector. If the length of the string is greater than the number, return 'String'. If the number is greater return 'Vector'. If they are both empty, return 'Empty'. If they are the same length, return 'Equal' Test Case: out= Compare('',[]) out -> 'Empty' out= Compare('CS1371', [2 3]) out ->'String' Solution: Problem: Function Name: study Input (1): Number of hours the person studied Output (1): A string commenting on their studying Description: The function study will take in a number of hours the person studies on a daily basis and study comments according to these conditions: If they study less than 4 hours each day say: 'I wish I had your schedule!'; If they study more than 4 but less than 10 hours say: 'Keep up the good work!'; If they study more than 10 hours say: 'You dont sleep do you?' and if the user does not enter in a valid input, say: 'Please enter hours of study' Test Cases: a = study(2) a --> 'I wish I had your schedule!' b = study(3) b --> 'Keep up the good work!' c = study(18) c --> You dont sleep do you? Solution: Problem: Write a function called switchAndIf. The inputs and outputs for the function are defined below: Inputs(1): a string that usually takes on the values discrete or range Outputs(1): a string indicating either the input was invalid or a string indicating when to use switch and if. Description: The function switchAndIf will indicate when to use switch and ifs based on the following conditions: If the following strings are inputted: 'discrete','menu','limited choices' then say: 'Using switch might be a good idea' if the following strings are inputted: 'range, does not check equality' then say: 'Using if might be a good idea' You must also return the string: "Invalid input" if the user does not enter a string as their input. You should return 'Invalid string' if the user inputs a string and it does not match up with the words stated (e.g. discrete, range, etc.) Solution: Problem: Function Name: slowSort Inputs (1): - (double) unsorted vector Outputs (1): - (double) sorted vector Function Description: Given an unsorted vector, sort it without calling the function sort. Use iteration. Test Case: out = slowSort([4 -1 0 5 2 5]) out -> [-1 0 2 4 5 5] Solution: Problem: Function Name: modCA Inputs (1): - (cell) a cell array Outputs (1): - (cell) the modified cell array Function Description: Given a cell array, delete the first and last cells. Then add 1 to anything that is of type double in the cell. Test Case: out = modCA({5, false, 'str', [4 3 2], {3}, 'hi'}); out -> {false, 'str', [5 4 3], {3}}; Solution: Problem: Name: locationsVec() Inputs: a vector Outputs: an array size 2 x number of elements in the vector Description: Use a loop( you must use it) through a vector and obtain the value and the position of that vector. Then outputs an array in such a way that the first row of that array is are the elements inside that vector and the second row contains the position of that element. Test Case: out1 = locationsVec([3, 1, 5]) out1 -> [ 3, 1, 5; 1, 2, 3] out2 = locationsVec([ 90, 101, -1, 7]) out2 -> [ 90, 101, -1, 7,; 1, 2, 3, 4,] Solution: Problem: Name:createArr() Inputs: a vector, number of rows(double), number of columns(double) Outputs: an array Description: Assuming the user inputs a valid number of rows and columns and also a vector, reshape the vector into the array of the specified dimensions of rows and columns. Test Cases: arr1 = createArr([ 1, 2, 3, 4, 5, 6],2,3) arr1 -> [ 1 2 3; 4 5 6] arr2 = createArr([9 1],2,1) arr2 -> [ 9;1] arr3 = createArr([ 91, 22, 80, 70, 41, -1, .5, pi], 4,2) arr3 -> [91, 22; 80, 70; 41,-1; .5, pi] Solution: Problem: Function Name: avgMinMax() Inputs(1): a string indicating the file's name Outputs(0): no outputs Function Description: Create a function that will take in a excel file contain student's test grades. You can assume the following about the excel file: 1. the first row is will always contain the student's names 2. the first column will also always contain what test the student took 3. second row and on , also the second column and on, you will find only numbers which represents the student's test scores. The function should add a header called 'Max Average' on the first column, two rows after the last test. The maximum average of the students should be stored in the column to the right. Below 'Max Average' should be 'Min Average' and to the right of that, should be the minimum student average. Finally, the function should write the file out to as an excel file with the same name as the original file name except the word 'Edited_' is now attached to the front of it. Test Case: avgMinMax('Student.xls') Student.xls looks like the following: 'Test/Name' 'Test 1' 'Test 2' 'Test 3' 'Test 4' [ [ [ [ 'Student 1' 61] 63] 100] 92] 'Student [ [ [ [ 2' 92] 79] 87] 92] 'Student 3' [ 82] [ 89] [ 84] [ 92] Edited_Student.xls should look like the following: 'Test/Name' 'Test 1' 'Test 2' 'Test 3' 'Test 4' [ [ [ [ 'Max Average' 'Min Average' 'Student 1' 61] 63] 100] 92] 'Student [ [ [ [ 2' 92] 79] 87] 92] 'Student 3' [ 82] [ 89] [ 84] [ 92] [87.5000] [79] Solution: Problem: Name: dropTest Inputs(1): A string indicating the file name Outputs(1): A cell array containing the strings of test names Description: Create a function that takes in file name. You can assume the following about the file: 1. the file's 1st row will always contain the students' names as strings. 2. the file's 1st column will always contain the names of the tests each student had to take 3. the 2nd column and on , also the 2nd row and on you can assume this area to be populated with students' scores (doubles). Your job is to determine the lowest test score for each student and then output a cell array containing the names of each of the students in the first row (should be in the same order as original data), and the test each student should drop in the second row. Scores.xls looks like the following: 'Test/Name' 'Student 1' 'Student 2' 'Student 3' 'Test 1' [ 61] [ 92] [ 92] 'Test 2' [ 63] [ 79] [ 89] 'Test 3' [ 100] [ 87] [ 84] 'Test 4' [ 92] [ 92] [ 82] out = dropTest('Scores.xls') out --> {'Student1', 'Student2', 'Student3'; 'Test 1', 'Test 2' , 'Test 4'} Solution: Problem: Function Name: dlmStats Inputs (3): (char)- a filname (char) - the delimiter (for reading in the file) (char) - the delimiter (for writing the file) Outputs (0) Function description: Write a function dlmStats which takes in an dlm file and outputs a modified dlm file. The delimiter will be specified in the second input. The inputted file will always have 4 columns. The first column will always be consecutive integers (i.e. 1, 2, 3, etc) that correspond to a given team. The second column will be the number of wins of that team in a given season The third column will be the total losses that season. The fourth column will the the number of ties. The function should create a new array that gives the following statistics all in the first row: 1 - the ID number of the team with the most wins 2 - the ID number of the team with the most losses 3 - the ID number of the team with the least ties Write this new array to delimited file which should have the same base name as the inputted name with '_new' added to the end. The new delimiter is specified in the third input Test case: dlmStats('scores.dlm', '!', '*') scores.dlm looks like the following: 1!13!0!1! 2!8!4!2! 3!2!7!5! 4!10!4!0! 5!0!13!1! scores_new.dlm should look like the following: 1*5*4 Solution: Problem: Function Name: xlsBaseball Inputs (1) (char)- a filname Outputs (0) Function description: Write a function xlsBaseball which takes in an excel file and outputs a modified excel file. The input excel file will always have 3 columns. This first column will always have 'Team' in the first row and the names of the teams under. The second column will always have 'Runs Scored' in the first row and the amount of runs scored by each team had under. The third column will always have 'Runs Allowed' in the first row and the amount of runs allowed by each team had under. The function should create a new array which is identical to the excel data except with one added row to the very bottom. In this row, the first column should contain 'Totals'. The second column should contain the total amount of runs scored. The third column should contain the total amount of runs allowed. Write this new array to an excel file which should be named the same as the input, but with the prefix 'new_' Test Case: xlsBaseball('baseball.xls') baseball.xls looks like the following: 'Team' 'Runs Scored' 'Runs Allowed' 'Us' 1024 4 'Them' 1 999 new_baseball.xls should look like the following: 'Team' 'Runs Scored' 'Runs Allowed' 'Us' 1024 4 'Them' 1 99 'Totals' 1025 103 Solution: Problem: Solution: Problem: Solution: Problem: Solution: Problem: Solution: Problem: Solution: Problem: Solution: Problem: Solution: Problem: 11. Character Strings (20 points) Write a MATLAB function called makeGTEmail that consumes two parameters: A character array representing the name of the person A domain representing the department the person is associated with. The rest of the email will always be gatech.edu. Any spaces in the name of the person should become a “.” in the email address. The function should return the character array of the newly formed email address. Assume any characters in the email address will always be lowercase. Examples: makeGTEmail(‘david smith’, ‘cc’); should return: ‘david.smith@cc.gatech.edu’ makeGTEmail(‘george p burdell’, ‘ece’); should return: ‘george.p.burdell@ece.gatech.edu’ makeGTEmail(‘clough’, ‘pres’); should return: ‘clough@pres.gatech.edu’ Problem 11 function ret = makeGTEmail(str1, str2) str1(find(str1==‘ ’)) = ‘.’; ret = [str1, ‘@’, str2, ‘.gatech.edu’]; Criteria 5 pts correct function header 4 pts finding the spaces correctly (Can use either find or iteration) 4 pts replacing correctly with a '.' 4 pts correct concatenation 3 pts returns the concatenated string (even if it is incorrect) 11. Character Strings (20 points) Write a MATLAB function called makeWebAddress that consumes two string parameters and produces a Web address in the form ‘http://www.DDDD.gatech.edu/PPPP, where DDDD is a department and PPPP the personal information. The parameters are: A string representing the name of the person A string representing the department the person is associated with. Any spaces in the name of the person should become a “.” in the email address. The function should return the character array of the newly formed web address. Examples: makeWebAddress(‘/fac/David Smith’, ‘cc’); should return: ‘http://www.cc.gatech.edu/fac/David.Smith’ makeWebAddress (‘~gt12345z’, ‘prism’); should return: ‘http://www.prism.gatech.edu/~gt12345z’ Problem 11 function ret = makeWebAddress(str1, str2) str1(find(str1==‘ ’)) = ‘.’; ret = [‘http://www.’, str2, ‘.gatech.edu/’, str1]; Criteria 5 pts correct function header 4 pts finding the spaces correctly (Can use either find or iteration) 4 pts replacing correctly with a '.' 4 pts correct concatenation 3 pts returns the concatenated string (even if it is incorrect) Problem 4 – Coding Problems [40 Points] 1. You are given a sound of a piano playing a C-note – 'cNote.wav'. Determine the number of seconds the sound plays for and store in the variable tnote. Then, plot the amplitude of the sound versus time. 2. Write a script to solve the following equations: 4x – 13y + 2z = 8 5y = z x – 5z = 42 3. Write a MATLAB function called makeGTEmail that consumes two parameters: A character array representing the name of the person A domain representing the department the person is associated with. The rest of the email will always be gatech.edu. Any spaces in the name of the person should become a “.” in the email address. The function should return the character array of the newly formed email address. Assume any characters in the email address will always be lowercase. Examples: makeGTEmail(‘david smith’, ‘cc’); should return: ‘david.smith@cc.gatech.edu’ makeGTEmail(‘george p burdell’, ‘ece’); should return: ‘george.p.burdell@ece.gatech.edu’ makeGTEmail(‘clough’, ‘pres’); should return: ‘clough@pres.gatech.edu’ 4. Given vectors x and y of equal length containing x and y data values, please do the following: - Compute the coefficients for a third order fit of the data and store in C - Create a new y vector called newy using this fit and the original x values - Compute the cumulative integral of newy using the trapezoidal rule - Plot the integral versus the x values Part 3 – Coding [40 points] 1. You are given a vector, temp, of temperature data that you want to “correct”. Your goal is to write a function named ‘fiddle’ that makes the temperature appear to be increasing over time. Your function should count the number of entries, N, below the average temperature. It should then add to those low temperatures in turn values that increase from 1 to N. For example: if temp is [ 67 42 97 84 35 37 67 28] The function fiddle will add [ 0 1 0 0 2 3 0 4] returning: [ 67 43 97 84 37 40 67 32] 2. Write a script to solve the following equations: 4x – 13y + 2z = 8 5y = z x – 5z = 42 3. You are given a set of x and y points, and are interested in the difference between a spline fit and a curve fit. Write a script that calculates the difference between the values of the spline fit and a curve fit of order 5 at values spaced 5 times closer than the original x data . 4. Write a function called myIsField. The function will take in a structure array and a string and will produce a logical result. If the field exists in the structure array then the function returns true. Otherwise it returns false. You may NOT use the isfield( ) function. Example: A = struct('name', 'Justin', 'favoriteclass', 'cs1371') ret = myIsField(A, 'name') ret: true 5. Write a function named insertSilence that consumes two inputs: the file name of a .wav file and the number of seconds of silence to insert, and returns nothing. This function should read the sound data, then split it into two halves and insert between the halves a vector of silence that will last for the number of seconds specified by the second parameter. The function should then plot the sound (with the silence inserted) in the time domain using a red line. Title your plot 'Inserted Silence' and label the x-axis 'time'. Test Case: insertSilence('saxophone.wav',3); Part 3 – Coding [40 points] 1. 'fiddle' function temp = fiddle(temp) avg = mean(temp); lows = temp < avg; N = length(find(lows)); temp(lows) = temp(lows) + (1:N); end 2. solve equations A = [4 -13 2 0 5 -1 1 0 -5] B = [8 0 42]' v = A \ B; x = v(1) y = v(2) z = v(3) 3. spline fit and a curve fit x = 1:5 y = sin(x) xi = linspace(x(1), x(end), 5*length(x)) diff = spline(x, y, xi) - ... polyval(polyfit(x, y, 5), xi) 4. myIsField function res = myIsField(sa, name) res = false; flds = fieldnames(sa); for ndx = 1:length(flds) if strcmp(name, flds{ndx}) res = true; break; end end end 5. insertSilence function insertSilence(name, t) [snd fs] = wavread(name); N = t * fs; snd = [snd(1:end/2); zeros(N,1); snd((n/2+1):end)]; plot(snd, 'r') title('Inserted Silence') xlabel('time') end