130 likes | 294 Views
COMP 116: Introduction to Scientific Programming . Lecture 23 : More Functions . Warmup : Sum and Product.
E N D
COMP 116: Introduction to Scientific Programming Lecture 23: More Functions
Warmup: Sum and Product • Write a function that would take as input a vector of any length. If it is empty print an error, if it is a row vector return the product of the entries it is a column vector return the sum of the entries. Use if, else, sum and prod • More fun: Use for loops instead of sum and prod
Problem #1: Temperature • (a) Write a function that converts a temperature in degrees Fahrenheit to its equivalent temperature in degrees Celcius. • (b) Call this function from a script that prompts (input) a user to enter a temperature, and then outputs the converted temperature. The script should keep running until no number is provided to convert (i.e., the user presses ‘Enter’)
Problem #2: Quadratic Equations • Given a quadratic equation: we can solve for x using this formula: • Write a MATLAB function solve_eqn which solves a quadratic equation, taking as input the values a, b and c. Call this function from a script file and try the following examples:
Problem #3: Vector manipulation • Write a function that would take as input a vector of any length, and convert each of its elements to either 0 or 5 according to the following rule: if the element is a negative number, convert to 0, if it is zero or positive, convert to 5. Use for, if, and else. • More fun: Write the function without using for loops.
Problem #4: Matrix manipulation • Write a function that would take as input a matrix (MxN), and convert each of its elements to either 0 or 5 according to the following rule: if the element is a negative number, convert to 0, if it is zero or positive, convert to 5. • More fun: No for loops
Problem #5: Continued fractions • Given a vector A = [a1 a2 a3 … an], a continued fraction is a number that looks like this: • Write a function that takes as input a row vector of any length, and evaluates the continued fraction that it represents.
Problem #6: Not in list • Given a list of numbers, find all the numbers between 1 and 9 that are not in that list, and return these numbers as a vector. Use find, for loops • More fun: Do this without using the findfunction
Problem #7: Approximating pi • Write a function that estimates pi by throwing N darts at a square -1 < x,y < 1, and counting the number that land inside the unit circle x^2+y^2<1. This fraction should approximate pi/4. • More fun: Color-code the darts and display as follows: darts that land inside the circle: red, darts that land outside the circle: blue