Submit your work in the form of a multiple .m files. To simplify the naming scheme of your .m files, please put your first initial and last initial (in lowercase letters) before each script or function name. This will make it easier for you to run and will look less cluttered in the future. For example, my file for the first problem would be jmGivePrimes.m
. If you are submitting a script file, start your file off with the command clear
and please clearly label and describe each problem with comments in your file.
Write a function GivePrimes
that takes as input a positive integer $a$ and returns 2 vectors $\mathbf{pr}$ and $\mathbf{notpr}$. The vector $\mathbf{pr}$ should contain all of the prime numbers less than or equal to $a$, and the vector $\mathbf{notpr}$ should contain all of the non-prime numbers less than or equal to $a$. Use the built-in isprime
function and logical indexing.
To make a function that returns more than one vector as an answer, you just need to use [output1,output2]
or [output1 output2]
as your outputs when defining the function.
For example, the first line of my function file will look like this:
function [pr, notpr] = jmGivePrimes(a)
To test your function, you will need to be sure and tell the computer that you want BOTH values to be returned in two separate variables. So, to call my function with $a = 10$ fomr the command window, I would type:
>> [pr,notpr] = jmGivePrimes(10)
Write a script file DoubleRandom
that creates a random $10\times 10$ matrix $A$ and doubles all the elements of $A$ between the values $0.2$ and $0.8$.
Error Checking. One common use of IF
statements is to check for errors in user input. For example, if you use the standard quadratic equation
$$
x = \dfrac{-b\pm \sqrt{b^{2} - 4ac}}{2a},
$$
with the value of $a=0$, you will have division by zero. With this in mind, create a function QuadEqCheck
that accepts as input variables $a$, $b$, and $c$, and returns the correct two solutions of the equation if $a\neq 0$, and returns the value $-c/b$ if $a = 0$. From where does the value $-c/b$ come and what solution are you giving in this situation?
Write a function CheckNegative
that accepts a vector $\mathbf{x}$ as its input. The function should return $\mathbf{x}$ if all of the elements of $\mathbf{x}$ are positive, but it should return $\mathbf{x}/2$ if any elements are negative.
HINT: You do not need to check each element individually. The command isneg = (x < 0 )
will return a vector with 1's and 0's. Use the built-in sum
command. What would be true if sum(isneg)
if $\mathbf{x}$ has any negative elements? What would be true if sum(isneg)
if $\mathbf{x}$ has no negative elements?
© 2020 Justin L. Mears
Your use of any material found at this site is subject to this
Creative Commons License.