CS 310 Exam 1

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Given temps = [8, 5, 6]. What is temps after the statement temps(0) = 7?

Error

The following command plots the points(100, 55) and (200, 45): plot([55, 45], [100, 200])

False. The array with x values must appear first: plot( [100, 200], [55, 45]).

Does 2 / 2 * 3 equal 2/6?

No

Does 2 / 3 ^2 equal 4/9?

No

In MATLAB, the % character is the only character that indicates a comment.

True

Within a function, the input variables names must match but you can use different input variable names outside of the function. The most important thing is that the order of the parameters being passed into a function match the parameterList order.

function returnValue = functionName (parameterList) returnValue = output of function Outside of function: outputValue = functionName(inputValues)

Using relational and arithmetic operators, complete the if-statement for each of the following situations. currPos is either less than lastPos or greater than lastPos

if (currPos ~= lastPos) % if statements go here end

Use trapz or integral function if only the discrete values are to be used.

trapz

Which statement divides each element in vec1 by 2?

vec1 / 2

Iterate until c is equal to the variable n.

while (c ~= n ) % loop body statements go here end

Given x = 22 and y = 99. What are x and y after the given code? >> tempVal = x; >> x = y; >> y = tempVal;

x is 99 and y is 22

In what order are the operators evaluated? w + 3 ~= y - 1 && x

+, ~=, -, && +, -, &&, ~= *+, -, ~=, &&*

Given sampleArray = [1, 3, 4, 4, 6] and resultArray = diff(sampleArray). If this results in an error type: Error. What is resultArray(3)?

0

Which approach uses a logical operator to detect if x is in the range 1 to 99.

0 < x < 100 *(0 < x) & (x < 100)* (0 < x) & (x >100)

(y < 3) || (x == 1) What value of y does NOT result in short circuit evaluation?

1 2 *3*

Given vec1 = [11, 8, 2, 5]. Which of the following statements calculates the multiplicative inverse of each element of vec1, namely 1/11, 1/8, 1/2, 1/5?

1 / vec1 *[1, 1, 1, 1] ./ vec1* vec1 .* [-1, -1, -1, -1] vec1 ./ [1, 1, 1, 1]

For each item below, indicate what the code will output. For an infinite loop, type: IL x=5; y=18; while (y >= x) fprintf('%d ',y); y = y - x; end

18 13 8 Note that there is a space after each number, including after the last number.

The following function purposely violates good practice in order to test understanding of the underlying concepts of a function: function out = PlusOne( inVar ) inVar = inVar + 1; out = inVar; end What is the value of inVar in the base workspace after executing: inVar = 1; inVar = PlusOne(inVar);

2. The function outputs 1+1 or 2, and inVar is assigned with the output.

If mat is a 3x5 matrix what does length(mat) output?

5 length() will output the larger value between the number of rows and columns

For a 5x4 matrix A, A(3:end, 3:end) will have how many elements?

6

Quiz 1: Which command will create the following matrix in MATLAB: A = 3 6 5 2 4 1 5 2 1 3 6 4 1 4 3 6 5 2

A = [[3 6 5 2 4 1] ; [5 2 1 3 6 4] ; [1 4 3 6 5 2]]

Addresses the elements in all rows between columns m and n of the array A

A(:, m:n)

Addresses all the elements in rows m1 to m2 and columns n1 to n2 of the array A

A(m1:m2, n1:n2)

Addresses the elements in all columns between rows m and n of the array A

A(m:n, :)

disp() only allows you to display 1 input parameter. How could you display multiple parameters?

By concatenating vectors/matrices. BUT EVERYTHING MUST BE SAME TYPE. ex: disp(['How many apples? ', num2str(5)]) How many apples? 5

Quiz 1: Given the following two matrices: A = [2 3 2 ; 3 1 2] B = [4 1 ; 2 3 ; 4 2] What is the value of C(2,2) where C = A*B (matrix multiplication)

C = [22 15 ; 22 10] So C(2,2) = 10

Given sensorReadings = [11, 33, 55, 77, 99], what are the resulting values in newArray? Type answers as: [1, 2, 3] (include commas). If appropriate, type: Error newArray = sensorReadings(2, 3, 5)

Error

Given sensorReadings = [11, 33, 55, 77, 99], what are the resulting values in newArray? Type answers as: [1, 2, 3] (include commas). If appropriate, type: Error newArray = sensorReadings(4:6)

Error

Given vals = [45, 55, 65, 75, 85, 95] newvals = vals(1:2:end) contains all even-number-indexed elements of vals, meaning [55, 75, 95].

False

An array to store the heights of 4 people would likely have 4 dimensions

False (there is only 1 dimension but 4 items)

Pseudo-code is MATLAB code that runs but isn't yet complete.

False. Pseudo-code is written in a programmer's native language (ex: English) and helps the programmer define the structure of a program. Pseudo-code does not run.

Given kmetersRun = 800, kmetersBiked = 2000, and kmDriven = 0.8 are floating-point numerical variables. An appropriate comparison method is abs(kmetersRun, 900) < 0.0001.

False. The abs function has one input. The input should be metersRun - 900 (replace comma with minus).

Given kmetersRun = 800, kmetersBiked = 2000, and kmDriven = 0.8 are floating-point numerical variables. If kmDriven2 is equal to 0.9, then abs(kmDriven - kmDriven2) < 0.0001 would return true, meaning the numbers are essentially equal.

False. The difference is 0.1, which is NOT less than 0.0001, so the result is false (meaning NOT equal; they are NOT close enough).

evenCols = xMat( 1:2:end, : ) contains all even columns of xMat

False. The first index points to odd rows, and the colon references all the columns. So, the correct answer is evenCols contains all odd rows of xMat.

How many iterations are performed by the following loop? num = -2; while( num < 10 ) num = 2 * num; end

Infinite loop

Does 2 + 3 * 4 - 4 equal 16?

No

Do xVal <= yVal, and yVal > xVal, yield the same result?

No. The second expression should be yVal >= xVal to yield the same result. Ex: xVal = yVal = 5 xVal <= yVal --> True yVal > xVal --> False yVal >= xVal --> True

Is this expression a proper way to detect if zVal is between 0 and 9? 0 < zVal < 9

No. This expression always yields true, due to being evaluated left-to-right: The first < will yield either 0 or 1, depending on zVal. The second comparison will thus be either 0 < 9, or 1 < 9, both of which are true. Expressions with relational operators can only be combined using logical operators.

What will the following statement display? C = 100 K = C + 273

Only C will display. Both C and K will display. *The statement results in an error.*

In a linear system, if the number of equations (m) is less than the number of unknowns (n)... m < n

Overdetermined. Redundant equations (so remove) or no solution (inconsistent info)

Which rows and columns are indexed in the following if mat is a 3x5 matrix? mat([1,2], 3)

Rows 1 & 2, column 3

Which rows and columns are indexed in the following if mat is a 3x5 matrix? mat([2,3,1], [4,1,5])

Rows 2, 1, 3 (in that order) Columns 4, 1, 5 (in that order)

Quiz 1: Given the following matrix: A = [4.56 6.32 7.1 3.7 6.2 5.9 4.7 ; 7.57 5.91 6.3 2.8 4.9 3.5 8.3] Which command subtracts the first row from the second row of this matrix and saves the results in a new variable S?

S = A(2, :) - A(1, :)

Quiz 1: (T/F) m-files are text only files that contain MATLAB commands and program statements

True

cityRain = [100,98,97 77,78,75] cityRain(3,1) = cityRain(4,4) generates an error.

True

A function provides isolation between i) the names used for the inputs and outputs defined in the function, and 2) the variable names used in the program segment calling the function.

True. A function creates a dedicated function workspace that is discarded when the function ends. In contrast, a script updates the base workspace.

Given kmetersRun = 800, kmetersBiked = 2000, and kmDriven = 0.8 are floating-point numerical variables. The comparison kmetersRun == kmetersBiked should be avoided.

True. Even though the variables are assigned integers, the variables are floating-point. Floating-point numbers should not be compared for equality.

Given kmetersRun = 800, kmetersBiked = 2000, and kmDriven = 0.8 are floating-point numerical variables. The comparison kmDriven == kmetersRun should be avoided.

True. Floating-point numbers should not be compared for equality due to rounding.

Using a double precision floating-point representation, the relative accuracy of variable aNum will never exceed eps(1)

True. The command eps(aNum) finds the absolute accuracy of the valued stored within the variable aNum. The relative accuracy is given by eps(aNum)/aNum and this value will never exceed eps(1)/1 or eps(1).

Assume nums = [-9.5, 300, 107.6, 0.3] nums < [212, 212, 212, 212] creates the logical array [1, 0, 1, 1]

True. The result is the same as nums < 212.

Placing critical code in a script enables quick testing of the code for various input values.

True. Variables could be set to new values and then the script re-run to generate new values.

In a linear system, if the number of equations (m) is greater than the number of unknowns (n)... m > n

Underdetermined. If a solution exists, it won't be unique (infinite solutions)

Does 2 ^ 3 ^ 2 equal 64?

Yes

Does w + x == y + z evaluate as (w + x) == (y + z)?

Yes

What is the vector created by: d = 10 : 2 : 1

[ ]

Assume variable avgHighNYC = [38.3, 41.6, 49.7, 61.2, 70.8, 79.3, 84.1, 82.6, 75.2, 63.8, 53.8, 43.0] represents average monthly high temperatures in Fahrenheit, thus having 12 elements (one per month, from January to December). What new array is created by lowTemps = (avgHighNYC(4:6) <= 73)? Type as: [0, 1, 1]

[1, 1, 0]

Quiz 2: A friend writes a function that converts meters into feet and inches. The first line of the function is: function [feet, inches] = convert_m_to_ft_in(m) Which of the following will call this function and convert 2.156 meters into feet and inches?

[feet, inches] = convert_m_to_ft_in(m = 2.156) *[ft, in] = convert_m_to_ft_in(2.156) convert_m_to_ft_in(2.156, m) convert_m_to_ft_in(ft, in, 2.156)

Quiz 1: If you do not assign a name to the result of an expression entered in the command window, what is the variable name that MATLAB assigns to the result?

ans

Type the command to set the x-axis limits from 5 to 10 and y-axis limits from 0 to 100.

axis([5, 10, 0, 100])

When an (m×n) matrix A and an (n×1) column vector b are multiplied, what is the length of Ab is equal to?

m

When a (1×m) row vector c and an (m×n) matrix A are multiplied, the length of cA is equal to?

n

Quiz 2: Which of the following MATLAB commands will create a plot showing the triangle whose vertices are at (1, 1), (4, 6), and (5, 2)?

plot([ 1, 1 ; 4, 6 ; 5, 2 ]) plot([1, 4, 5], [1, 6, 2]) plot([1, 1], [4, 6], [5, 2]) *plot([1, 4, 5, 1], [1, 6, 2, 1]) plot([1, 1], [4, 6], [5, 2], [1, 1]) *note: need 4 points to create closed triangle

Write a statement that plots a row array x, slope m, and intercept b as a cyan dashed line with line width 3.

plot(x, m * x + b, 'c--', 'LineWidth', 3)

Precision is the number of digits to the right of the decimal point that _______.

will always be displayed. If the number has more digits, the digits will be rounded. If the number has fewer digits, 0s will be appended.

Type the command to set the x-axis label to: Speed.

xlabel('Speed')

Which operator is evaluated first? ~y && x

&& *~*

Given nums = [19, 23]. What is nums after the statement nums(2) = 34?

[19,34]

How many iterations are performed by the following loop? num = 2; while( num > 10 ) num = 2 * num; end

0

Loop iterates 95 times. i = 1; while ( i < ____) % Loop body statements go here i = i + 1; end

96

Given ages = [20, 26]. What is ages after the statement ages(5) = 40?

[20, 26, 0, 0, 40]

Matt Labler is a novice MATLAB programmer. He wants to set variable A to 6, B to 9, and C to their sum, with only the values of A and C displaying in the command window. He asks you to check the following statement for bugs: A = 6; B = 9; C = A + B

a. The code is correct as is. *b. Matt should use "A = 6, B = 9; C = A + B" instead.* c. Matt should use "A =6; B = 9, C = A + B;" instead.

What will the following statement display? X = 39; Y = 41, Z = X + 17,;

a. The statement results in an error. b. Only Y is displayed. *c. Only Y and Z are displayed.* **The same output could be obtained by: X = 39; Y = 41, Z = X + 17

Obtain the backward difference of the function by using the diff function and the element-by-element division operator.

backwardDiff = diff(yValues) ./ diff(xValues)

Clients are billed for hours in one hour increments. The policy of the office is to never round up.

ceil *floor* fix round

Indicate which rounding functions are the most appropriate in the following scenarios. Report the temperature to the nearest integer.

ceil floor fix *round*

num2str()

convert number to string

myArray = [20:4]

creates an empty 1x0 array

Which statement divides each element in rowEx = [4, 5, 6] by 2?

*rowEx / 2* rowEx / [2, 2, 2] rowEx ./ (2, 2, 2) Also, rowEx ./ 2 and rowEx ./ [2, 2, 2] work. Performs element-wise division by 2. The dot is optional when a scalar is involved.

How will the following expression execute?~startPos+trackLen < 5

((~startPos) + trackLen) < 5

Which illustrates the actual order of evaluation via parentheses? bats < birds || birds < insects

(bats < birds) || (birds < insects)

Which illustrates the actual order of evaluation via parentheses? (num1 == 9) || (num2 == 0) && (num3 == 0)

(num1 == 9) || ((num2 == 0) && (num3 == 0))

How will the following expression execute? usrSw1 & swMask1 == usrSw2 & swMask2

(usrSw1 & (swMask1 == usrSw2)) & swMask2

Which detects if x is either less than -5, or greater than 10?

(x < -5) & (x > 10) *(x <-5) | (x > 10)* ( x > -5) | (x > 10)

Which detects if x is in the range -4 to +4?

(x <-5) & (x < 5) (x > -5) | (x < 5) *(x > -5) & (x < 5)*

A programmer erroneously wrote an expression as: 0 < x < 10. Rewrite the expression using logical AND. Use parentheses.

(x > 0 ) && (x < 10)

((x > 2) || (y < 4)) && (z == 10) Given x = 4, y = 1, and z = 10, which comparisons are evaluated?

(x>2), (y < 4), and (z==10) *(x>2) and (z==10)* (x>2) and (y < 4)

Which illustrates the actual order of evaluation via parentheses? ~ (bats < birds) || (birds < insects)

(~ (bats < birds)) || (birds < insects)

Which illustrates the actual order of evaluation via parentheses? ~green == red

(~green) == red

How will the following expression execute? ~xPos==2

(~xPos) == 2

Quiz 1: Which of the following command(s) can be used to create the following vector? B = [-100 -103 -106 -109 -112 -115 -118]

*B = -[100 : 3 : 18]* *B = - 100 : -3 : -120* B = -1 * [118 : -3: 110] B = -1 * (120 : 3 : 100) B = -118 : 3 : 100 *B = -100 : -3 : -118*

Indicate which rounding functions are the most appropriate in the following scenarios. A parking lot charges $2/hour and they round to the next hour.

*ceil* floor fix round

How many iterations are performed by the following loop (i.e., how many times is the loop body executed)? num = 2; while( num < 10 ) num = 2 * num; end

3

Loop iterates 2 times. (Use the smallest possible integer value) i = 1; while ( i < 11 ) % Loop body statements go here i = i + ____; end

5

Given the following code, how many times will the fprintf statement execute?i1 = 1; while (i1 < 19) i2 = 3; while (i2 <= 9) fprintf('%d%d ', i1, i2); i2 = i2 + 3; end i1 = i1 + 10; end

6

Loop iterates from -100 to 31 (inclusive). i = -100; while ( i ___ 32 ) % Loop body statements go here i = i + 1; end

<

What does x = myArray(0) output?

Error

Given sampleArray = [1, 3, 4, 4, 6] and resultArray = diff(sampleArray). If this results in an error type: Error. What is resultArray(5)?

Error. sampleArray has five elements, so resultArray only has four elements.

A comment is only valid if preceded by a MATLAB statement on the same line.

False

A second % ends a comment, thus enabling a statement to appear after a comment on a line, as in:% Increment total % total = total + 1;

False

MATLAB's interpreter makes testing pieces of code especially difficult.

False

The variables created by the script are eliminated from the base workspace after the script runs.

False

cityRain = [100,98,97 77,78,75] currRain = cityRain(3, 1) yields 97.

False

Incremental programming is good practice for beginners, but experienced programmers type large amounts of code between tests.

False.

A local function can appear anywhere in a script.

False. A local function must be at the end of the script.

Each script has a workspace dedicated to that script.

False. All scripts share the base workspace.

Assume nums = [-9.5, 300, 107.6, 0.3] nums == (0.1 + 0.2) creates the logical array [0, 0, 0, 1]

False. Recall from another section that floating-point numbers should not be compared for equality, due to rounding issues. In this case, the representation of 0.1 + 0.2 does not exactly equal the representation for 0.3. Therefore, the result is [0, 0, 0, 0]. Instead, floating-point numbers should be compared for being "close enough".

Using a double precision floating-point representation, the error in absolute accuracy of the variable aNum will never exceed eps.

False. The absolute accuracy of a number represented in floating point, which is given by eps(aNum), decreases with the magnitude of aNum. Stated differently, the absolute error gets larger with the magnitude of aNum. It is the relative accuracy that will be bounded by eps(1).

Given xRow = [3, 1, 4, 1], the statements: xRow + xRow xRow .* [1, 1, 1, 1] + xRow 2 * xRow 2 * [1, 1, 1, 1] .* xRow all yield the same result.

True. All those statements multiply xRow by 2 in an element-wise manner.

The base workspace stores variables that are created at the command line.

True. All variables created at the command line are stored in the base workspace. Remember that any variables created inside a function itself are local to the function and will not be seen in the base workspace.

Given kmetersRun = 800, kmetersBiked = 2000, and kmDriven = 0.8 are floating-point numerical variables. If kmDriven2 is equal to 0.80000001, then abs(kmDriven - kmDriven2) < 0.0001 would return true, meaning the numbers are essentially equal.

True. The difference is 0.00000001, which is less than 0.0001, so the result is true (meaning equal; they are close enough).

Does -4 ^ 2 equal -16?

Yes

Write an expression such that the logical variable onTime is true if noTraffic is true and gasEmpty is false.

onTime = noTraffic > gasEmpty Will only evaluate to true when noTraffic is true (1) and gasEmpty is false (0)

Suppose x is a row array, m is a scalar variable equal to the slope of a line, and b is a scalar variable equal to the y-intercept. Write a statement that plots a cyan line for a row array x, slope m, and intercept b.

plot(x, m * x + b, 'c')

Type the command to plot the points stored in arrays xvals and yvals, drawing points as circles and with no line segments.

plot(xvals, yvals, 'o')

(x < 3) && (y < 2) && (z == 5) What values of x and y do NOT result in short circuit evaluation?

x=2, y=2 *x=1, y=0* x=4, y=1 x=3, y=2

Given sensorReadings = [11, 33, 55, 77, 99], what are the resulting values in newArray? Type answers as: [1, 2, 3] (include commas). If appropriate, type: Error newArray = sensorReadings([1:3, 5])

[11, 33, 55, 99]

Given sensorReadings = [11, 33, 55, 77, 99], what are the resulting values in newArray? Type answers as: [1, 2, 3] (include commas). If appropriate, type: Error newArray = sensorReadings([1, 3])

[11, 55]

Suppose n = 1. For xRow = [20, 70], what is xRow after: xRow(n + 3) = 10

[20, 70, 0, 10]

Assume sampleMatrix = [ 1,2,3,4; 5,6,7,8 ]. Write arrays as [ 1, 2; 3, 4 ]. For z = size(sampleMatrix'), what is the value of z?

[4, 2]

Given vals = [42, 77]. What is vals after the statement vals(3) = 82?

[42, 77, 82]

Given sensorReadings = [11, 33, 55, 77, 99], what are the resulting values in newArray? Type answers as: [1, 2, 3] (include commas). If appropriate, type: Error newArray = sensorReadings(3:-1:1)

[55, 33, 11]

Given sensorReadings = [11, 33, 55, 77, 99], what are the resulting values in newArray? Type answers as: [1, 2, 3] (include commas). If appropriate, type: Error newArray = sensorReadings(3:5)

[55, 77, 99]

Write a custom function CheckSquare() to check if a 2D array is square. A 2D array is square if the number of rows equals the number of columns. function [ isSquare ] = CheckSquare(arrayIn1) % Checks if an array is square % and set isSquare to true if the % input array is square, else false. [rnum,cnum] = ________________ isSquare = __________________; end

[rnum,cnum] = size(arrayIn1) isSquare = rnum == cnum;

Indicate which rounding functions are the most appropriate in the following scenarios. A diver's depth gauge reports the depth in meters in negative integers. What is the most conservative estimate of the depth of the diver?

ceil *floor* fix round Rounds to the nearest integer less than or equal to the element. Appropriate in this case.

Type the first line of a function definition for a function named CubeNum with input xVal and output yVal .

function yVal = CubeNum(xVal)

For xRow = [20, 70, 10], what initial value of n below yields [20, 70, 10, 80]? n = n + 1; xRow(n) = 80;

3

The following lists the heights in meters of the two tallest mountains in Asia, South America, and North America: In the array below, the columns correspond to the heights and the rows correspond to the continents. topMounts = [ 8848, 8611; 6962, 6893; 6194, 5959; ] What result is returned by evaluating the following: topMounts(3,:) = [ 9934, 9321, 8989 ]

Error

For the function definition beginning as shown below, are the following function calls likely to behave as a programmer intended? function [ surfaceArea, baseArea, vol ] = ConeVals ( radius, height ) [ vol ] = ConeVals ( rds, hght );

No. The surfaceArea output will be written into vol, which is likely not what the programmer intended.

cityRain = [100,98,97 77,78,75] currRain = cityRain(7) generates an error.

True

myArray = [ [1, 2, 3]; [4, 5, 6 ]] creates the matrix [1,2,3 4,5,6]

True

myArray(5; 4) accesses the element in row 5, column 4.

True

testMatrix( : , : ) = k assigns all the values in testMatrix to scalar value k.

True

Complete the statement below so that the function returns the ratio of two input argument functions evaluated at scalar value xVal. function [ result ] = FunRatio( numerFun, denomFun, xVal ) % Calculates the ratio of two functions % numerFun(xVal)/denomFun(xVal). % numerFun and denomFun are function handles. result = __________________________________;

feval(numerFun, xVal) / feval(denomFun, xVal)

Write a statement that assigns variable myNum with the result of a call to the function defined below with arguments 3 and 9function o1 = CalcR( i1, i2 )

myNum = CalcR(3,9)

Assign elements 4 and 5 of newArray with [10, 20]. Use the colon operator with a default increment.

newArray (4:5) = [10, 20];

Assign elements 1, 2, and 4 of newArray with [13, 7, 5] using an indexing array.

newArray ([1, 2, 4]) = [13, 7, 5];

Which operator is evaluated first? w + 3 > x - y * z

+ - > * (answer)

Which are valid relational operators in MATLAB? 1. < 2. =< 3. = 4. ~= 5. <> 6. ~<

1. Valid 2. Invalid 3. Invalid 4. Valid 5. Invalid 6. Invalid

Which are valid identifiers? 1. r2d2 2. name$ 3. _2a 4. pay-day 5. 2a 6. y_____5 7. switch

1. Yes 2. No 3. No 4. No 5. No 6. Yes 7. No

Loop iterates 10 times. i = 1; while ( i <= ____) % Loop body statements go here i = i + 1; end

10

Assume variable avgHighNYC = [38.3, 41.6, 49.7, 61.2, 70.8, 79.3, 84.1, 82.6, 75.2, 63.8, 53.8, 43.0] represents average monthly high temperatures in Fahrenheit, thus having 12 elements (one per month, from January to December). How many elements are in the logical array created by acOnMonths = (avgHighNYC >= 70 )?

12

Given the following code, how many times will the fprintf statement execute? i1 = 0; while (i1 < 3) i2 = 1; while (i2 <= 7) fprintf('%d%d ', i1, i2); i2 = i2 + 2; end i1 = i1 + 1; end

12

What is the output of the following code? i1 = 1; while (i1 < 19) i2 = 3; while (i2 <= 9) fprintf('%d%d ', i1, i2); i2 = i2 + 3; end i1 = i1 + 10; end

13 16 19 113 116 119 *Note there is a space after 119

What is the value of num after the following loop terminates? num = 1; while( num < 10 ) num = 2 * num; end

16

Given sampleArray = [1, 3, 4, 4, 6] and resultArray = diff(sampleArray). If this results in an error type: Error. What is resultArray(1)?

2

(y == 3) || (x > 2) What value of y results in short circuit evaluation?

2 *3* 4

(x < 4) && (y > 3)What value of x results in short circuit evaluation?

2 3 *6*

Given kmetersRun = 800, kmetersBiked = 2000, and kmDriven = 0.8 are floating-point numerical variables. abs(kmDriven - 0.5) < 0.0001 would be OK, but abs(0.5 - kmDriven) < 0.0001 would not due to the negative result.

False. The absolute value function makes the result independent of the ordering. 0.5 - 0.8 is -0.3, whose absolute value is 0.3. 0.3 is not less than 0.0001, so the result is false.

To what does this expression evaluate, given int x = 4, int y = 7. x == 3 || x + 1 > y

False. The arithmetic operator has highest precedence, yielding x == 3 || 5 > y. Next is the relational operator >, yielding x == 3 || false (because 5 > 7 is false). Next is ==, yielding false || false. Finally, the || is evaluated, yielding false.

Given kmetersRun = 800, kmetersBiked = 2000, and kmDriven = 0.8 are floating-point numerical variables. An appropriate comparison method is abs(kmDriven - 0.5) < 1.

False. The threshold is too large for the numbers involved. 0.8 - 0.5 would be 0.3, which is less than 1, so the result is true, meaning 0.8 and 0.5 are considered equal -- certainly not the programmer's intent.

For each item below, indicate what the code will output. For an infinite loop, type: IL x = 10; while (x ~= 3) fprintf('%d ',x); x = x / 2; end

IL

What is the difference between log() and log10() in MATLAB?

MATLAB log() is the natural log (ln) log10() is log base 10

Does w && x == y && z evaluate as (w && x) == (y && z)?

No the expression evaluates as (w && (x == y)) && z

Does ~x == 3 evaluate as ~(x == 3)?

No the expression evaluates as (~x) == 3

Entering the following command line is allowed: CostDrive; CostDrive

True. A script may be run multiple times. And a script's name may be followed by a semicolon, which has no effect. In this case, the script would run twice.

In a linear system, if the number of equations (m) is equal to the number of unknowns (n)... m = n

The linear system might have a unique solution

A matrix that is both upper and lower triangular is a diagonal matrix.

True

Always supress the output inside a function using (;)

True

Cannot assign a variable to disp()

True

Element-wise operations between compatible sized row and column arrays should be avoided even though the operations are allowed in MATLAB.

True

Element-wise operators can be used for scalars, vectors, or matrices

True

Incremental programming involves writing and testing a program in small increments.

True

Never put a display command inside a function

True

Two numerical array inputs have compatible sizes if, for every dimension, the dimension sizes of the inputs are either identical or any one of the array sizes is 1.

True

Assume nums = [-9.5, 300, 107.6, 0.3] smallLocs = (nums < 3); smallNums = nums(smallLocs) creates [-9.5, 0.3].

True.

For the function definition beginning as shown below, are the following function calls likely to behave as a programmer intended? function [ surfaceArea, baseArea, vol ] = ConeVals ( radius, height ) [ surfArea ] = ConeVals ( rds, hght );

Yes. The last two outputs will simply be ignored, which is OK if the programmer just needs the surface area output.

Does a logical variable represent the values true or false?

Yes. True is typically 1, false is always 0.

Which statement calculates the multiplicative inverse of each element in vec1?

[1, 1, 1, 1] ./ vec1

What is the value of xRow = [20, 70] after executing: n = 3; xRow(n) = 15;

[20, 70, 15]

Given locs = (avgHighNYC > 80), what new array is created by hotTemps = avgHighNYC(locs)?

[84.1, 82.6]

Assume variable avgHighNYC = [38.3, 41.6, 49.7, 61.2, 70.8, 79.3, 84.1, 82.6, 75.2, 63.8, 53.8, 43.0] represents average monthly high temperatures in Fahrenheit, thus having 12 elements (one per month, from January to December). Write an expression that assigns logical array variable acOnMonths with true wherever the average monthly high is above 70 degrees Fahrenheit.

acOnMonths = (avgHighNYC > 70)

Within a function, the return variable names must match but you can assign this output to a different variable name outside of the function.

function returnValue = functionName (parameterList) returnValue = output of function Outside of function: outputValue = functionName(inputValues)

Loop iterates over the odd integers from 0 to 9 (inclusive). i = 1; while ( i <= 9 ) % Loop body statements go here i = _________; end

i + 2

Loop iterates over multiples of 5 from 0 to 1000 (inclusive). i = 0; while ( i <= 1000 ) % Loop body statements go here i = __________; end

i - 1

Using relational and arithmetic operators, complete the if-statement for each of the following situations. startPos is not less than endPos

if (startPos >= endPos) % if statements go here end

Use trapz or integral function if a spline interpolation to the dataset is available.

integral

Never put clear inside a fucntion

it will clear the input parameter values

Pre-allocation of an array before a loop with many iterations is executed, as opposed to repeatedly re-allocating the array inside the loop, _____

makes the code more readable. does not make a difference in execution speed. *makes the code execute faster.*

Test if numDogs is either less than or greater than numCats.

numDogs ~= numCats

Quiz 2: Suppose we have a function named insideTri that accepts three row vector arguments in this order: - a row vector that contains the x and y-coordinate of a single point - a row vector that contains the x-coordinates of a triangle - a row vector that contains the y-coordinates of a triangle The function returns 1 if the point is in the triangle, 0.5 if the point is on the border of the triangle, and 0 if the point is outside the triangle. Which of the following the MATLAB commands will correctly call the function to determine if the point (1,0) is inside the triangle at vertices (2,-2), (3,4), and (-1,-3) and assigns the value the function returns to the variable result?

result = insideTri([2, 3, -1], [-2, 4, -3], [1, 0]) result = insideTri((1, 0), (2, -2), (3, 4), (-1, -3)) result = insideTri((1, 0), (2, 3, -1), (-2, 4, -3)) *result = insideTri([1, 0], [2, 3, -1], [-2, 4, -3]) result = insideTri([1, 0], [2, -2], [3, 4], [-1, -3])

Pre-allocation of an array before a loop is executed can be performed with _____

the size function. *the ones function.*

Pre-allocation of an array before a loop is executed can be performed with _____

the zero function. *the zeros function.*

Write a single-operator expression using a scalar operand that sets all elements of the row array vals = [1, 0, 1, 0] to true.

vals = vals | 1 The scalar 1 (true) is applied to each element of x using the or operator. The assignment operator overwrites the original contents of array vals with the resulting array.

If vec = [5, 2, 1, 6, 3] then what does the expression vec(1, 3) = 4 do?

vec = [5, 2, 4, 6, 3] Note: linear indexing (vec(3) = 4) could be used here since there is only one row.

Quiz 2: We wish to define a function volumeSphere that has one parameter, the radius of a sphere, and returns the volume of the sphere. Which of the following will correctly complete the definition of the volumeSphere function so that it works for vector as well as scalar input? The code is placed into a file named volumeSphere.m where the function header (first line of the function definition) is: function vol = volumeSphere(r)

volumeSphere = 4/3*.pi*.r^.3; volume = 4/3.*pi.*r.^3; vol = 4/3.*pi.*r^3; *vol = 4/3*pi*r.^3; volumeSphere = 4./3.*Pi.*r.^3;

How to solve a linear system in MATLAB?

x = A\b (left divide) where the output is a column vector of numeric values for x. Note: b/A = A\b in MATLAB

Quiz 2: Consider the following two MATLAB function definitions: function x = two_roots(a, b, c) % Returns the roots of the polynomial % y = Ax^2 + Bx + C sol1 = (-b + sqrt(b^2 - 4*a*c)) / (2*a); sol2 = (-b - sqrt(b^2 - 4*a*c)) / (2*a); x = [sol1 sol2]; function xroots = plot_quad(a, b, c, xrange) % Plots the quadratic equation y = Ax^2 + Bx + c % from -xrange to xrange. % Also, plots the points where it crosses the x-axis and % returns the roots of the polynomial xx = -xrange:0.1:xrange; yy = a*xx.^2 + b*xx + c; CODE yroots = a*xroots.^2 + b*xroots + c; plot( xx,yy, [-xrange xrange],[0 0], xroots,yroots,'o'); Which code choice replaces the line CODE, in the second function definition, so that the second function correctly calls the first function to find the roots of the quadratic polynomial?

x = two_roots(a,b,c); *xroots = two_roots(a,b,c); xroots = two_roots(2,3,-14); x = two_roots(2,3,-14); xx = two_roots(a,b,c); xx = two_roots(2,3,-14);

For the following (x,y) data points, (1,3) and (2,5), the backward difference estimates the numerical derivative at

x=0.0 x=1.0 *x=1.5* The backward difference estimate is found at the midpoint between the first and the second x-value. 1.5 is between 1 and 2.

For the following (x,y) data points, (1,3), (1.5,2) and (2,5), the central difference estimates the numerical derivative at

x=1.0 *x=1.5* x=2.0 The central difference estimate is found at the midpoint between the first and the third x-value

cityRain = [100,98,97 77,78,75] cityRain(3, 1) = 44 generates an error.

False

cityRain = [100,98,97 77,78,75] currRain = cityRain(5) generates an error.

False

myArray = [ [1, 2], [3, 4], [5, 6] ] creates the matrix: [1,2 3,4 5,6]

False

myArray = [ [1, 2]; [4, 5, 6] ] creates the matrix [1,2,0 4,5,6]

False

myArray[2, 3] accesses the element in row 2, column 3.

False

The script testScript contains a local function fixEverything. The function fixEverything can be called from the command line.

False. A local function can only be called from within the script that contains the function.

A function that outputs an array requires extra brackets compared to a function that outputs a scalar.

False. A scalar is treated as a 1x1 array, so no extra brackets are necessary.

Defining a custom function whose input is a numerical array requires more brackets than if the input was a scalar.

False. A scalar is treated as a 1x1 array, so no extra brackets are necessary.

The following command plots the points (10, 99) and (20, 88): plot([10, 99], [20, 88])

False. All x values must be in first array, y values in second: plot( [10, 20], [99, 88] ).

Consider the equation a1x1+a2x2^2=c If a1 and a2 are constant coefficients, the equation describes a linear relationship with variables x1 and x2.

False. In this scenario, the variables do not appear in the first power. While the equation is linear with respect to the variable x1, the equation is not linear in the variable x2.

Given sampleVals = [9, 10, 11, 12; 13, 14, 15, 16], sampleVals(:, end) returns 16

False. The : refers to all rows, the end to the last column. So the result is [12; 16]

Given sampleVals = [5, 6, 7; 9, 10, 11; 14, 15, 16],sampleVals(:, 2:end) returns [9, 10, 11; 14, 15, 16]

False. The : refers to all rows. The 2:end refers to columns 2 and 3. So all rows in columns 2 and 3 are: [6, 7; 10, 11; 15, 16]

A function whose output is [x, y] indicates output of an array with two scalar values.

False. The [x, y] indicates two outputs. x and y might be arrays.

Given a linear set of equations Ax=b, where A is a square matrix, calculating the inverse of the matrix A is an efficient way to solve the set of equations numerically.

False. The inverse of the matrix A should never be numerically calculated. Other numerical techniques are more efficient for solving a linear set of equations.

The following command generates an error because the x points are not in ascending order: plot([2, 5, 3], [4, 6, 7])

False. The plotted points are (2,4), (5,6), and (3,7). No error is generated, but the plot's lines will connect (2,4) with (5,6), and (5,6) with (3,7), causing a zigzag appearance (like the shape >).

Given bRow = linspace(1, 3, 3). xRow and yRow will be equal after executing xRow = bRow ^ 2; yRow = bRow .* bRow.

False. The xRow statement generates an error due to the missing dot. If using .^ instead, then the two results would be the same, both squaring each element.

Consider the following multiplication table of the first five integers stored as a 5 × 5 array, where the element stored at index (a,b) is the product a × b: timesTable = [1,2,3,4,5 2,4,6,8,10 3,6,9,12,15 4,8,12,16,20 5,10,15,20,25] What does the following return? row5 = timesTable( 5, : ); row5(1:2:5)

*[ 5, 15, 25 ]* [ 5; 15; 25; ] [ 5, 10, 15, 20, 25 ] an error

Consider the following multiplication table of the first five integers stored as a 5 × 5 array, where the element stored at index (a,b) is the product a × b: timesTable = [1,2,3,4,5 2,4,6,8,10 3,6,9,12,15 4,8,12,16,20 5,10,15,20,25] Which statement returns the products of the first five integers with 3 and 4 as a 2 × 5 array?

*timesTable(3:4, :)* timesTable(:, 3:4) timesTable(3, 4) timesTable(3:4, 3:4)

Indicate if the following arrays dimensions are compatible in size to perform an element by element operation: 1. (3x5) and (3x5) 2. (3x5) and (5x3) 3. (1x5) and (6x5) 4. (3x2) and (5x3) 5. (6x5) and (6x1)

1. T 2. F 3. T 4. F 5. T

The following function purposely violates good practice in order to test understanding of the underlying concepts of a function: function out = PlusOne( inVar ) inVar = inVar + 1; out = inVar; end What is the value of inVar in the base workspace after executing: inVar = 1; out1 = PlusOne(inVar);

1. The inVar inside the function PlusOne is in a local workspace. So, inVar in the base workspace is not changed.

Complete the statement to produce the following array: 2,-1,0,3,3 -1,2,-1,3,3 0,-1,2,2,3 0,0,-1,2,-1 0,0,0,-1,2 sampleMatrix = 2 * eye(5); sampleMatrix(1:4,2:5) = sampleMatrix(1:4,2:5) - 1*eye(4); sampleMatrix(2:5,1:4) = sampleMatrix(2:5,1:4) - 1*eye(4); sampleMatrix(1:3,4:5) = sampleMatrix(1:3,4:5) + ___________;

3 * ones(3,2)

If xRow is initially [20, 70, 60, 80, 90], what is xRow after: xRow(6) = []

Error

All element-wise MATLAB operators end with a period.

False

Given vals = [45, 55, 65, 75, 85, 95] newvals = vals(end:-1:end-3) extracts the last three elements in vals and report them in reverse order, meaning [95, 85, 75].

False

If A and B are arrays of same size, then A .+ B is a valid MATLAB expression.

False

The number of columns and rows in a matrix can change under an element-element operator.

False

The linear set of equations a11x1+a12x2=0 a21x1+a22x2=0 is only sometimes consistent.

False. This set of equations will always have trivial solution x=0, and thus will always be consistent. Additional solutions may exist. This example is known as a homogeneous set of equations. A homogeneous set of equations always has at least a trivial solution x=0 and therefore is always consistent.

Assuming the function FunRatio() defined above works correctly, write a statement using FunRatio() to calculate the tangent of pi/3.

FunRatio(@sin,@cos,pi/3) Tangent is equivalent to the ratio of sine over cosine. FunRatio() must be called with function handles that indicate these two built-in functions.

For the function definition beginning as shown below, are the following function calls likely to behave as a programmer intended? function [ surfaceArea, baseArea, vol ] = ConeVals ( radius, height ) [ baseArea, surfaceArea, vol ] = ConeVals ( rds, hght );

No. The programmer likely reversed the result variables baseArea and surfaceArea.

If A is an array and c is a scalar, c.*A equals c*A

True

cityRain = [100,98,97 77,78,75] cityRain(7) = 55 generates an error.

True

Given aRow = 1:1:3.The arrays xRow and yRow will be equal after executing xRow = aRow - 1; yRow = aRow - [1, 1, 1] .

True. Both statements subtract 1 from each element, resulting in [0, 1, 2].

The following command generates an error because the array lengths differ: plot( [2, 4, 6], [99, 88] )

True. The array lengths must be equal; together the arrays represent the x/y values of a sequence of points.

Consider the equation a1x1+a2x2^2=c If x1 and x2 are known numbers, the equation describes a linear relationship with variables a1 and a2.

True. To determine if an equation is linear with respect to a quantity, one can identify the known and unknown parameters in the equation. x2^2 evaluates to a constant. All the constant coefficients of the equation are numbers. The variables (a1, a2) are raised to the first power.

Assign elements 60, 10, and 70 of newArray with elements 10, 20, 30 of fixedArray.

newArray([60, 10, 70]) = fixedArray([10, 20, 30]);

Assume dataVec = [ 0.0, 0.6, 0.63, 0.9, 0.91, 1.03 ]. Write arrays as [ 1, 2, 3 ]. Using the sum function, write a statement that computes the average of all the elements of dataVec.

sum(dataVec) / length(dataVec)

The following lists the heights in meters of the two tallest mountains in Asia, South America, and North America: In the array below, the columns correspond to the heights and the rows correspond to the continents. topMounts = [ 8848, 8611; 6962, 6893; 6194, 5959; ] Suppose africaMts is a 1 × 2 array storing the heights in meters of the two tallest mountains in Africa. Write an expression that returns an array with the data for South America replaced by the data for Africa.

topMounts(2,:) = africaMts

The following lists the heights in meters of the two tallest mountains in Asia, South America, and North America: In the array below, the columns correspond to the heights and the rows correspond to the continents. topMounts = [ 8848, 8611; 6962, 6893; 6194, 5959; ] Use the single colon operator and write arrays as [ 1, 2; 3, 4 ]. If appropriate, type: Error. Do not end with a semicolon. Write an expression that replaces the heights of the tallest mountain in each continent with the values 8850, 6963, and 6192.

topMounts(: , 1) = [8850; 6963; 6192]

Given nums = [1, 2]. Which yields a vertcat error?

vals = [nums, [3, 4]] vals = [nums, [3; 4]] vals = [nums; [3, 4]] *vals = [nums; [3; 4]]*

Given row array vals of unknown size of 2 or greater, write an expression that yields a new array containing all elements except the first. For example, if vals = [10, 20, 30, 40], the expression would yield [20, 30, 40].

vals(2:end)

Write an expression that results in a row array vals shifted to the right. For example, if vals = [1,2,3,.....,n-1,n], then a right shift will result in [n,1,2,3,.....,n-1].

vals([end, 1:end-1])

Given vec1 = [-9, 4, -7, 3]. Which of the following statements is equivalent to taking the absolute value of each element of vec1?

vec1 .* [-1, -1, -1, -1] vec1 ./ [1, -1, 1, -1] *(vec1 .* vec1) .^ (1/2)* vec1 ./ vec1

Write a statement that concatenates row array newVals to the end of row array xRow. Ex: If newVals is [10, 12] and xRow is [20, 70, 60], then xRow becomes [20, 70, 60, 10, 12].

xRow = [xRow, newVals]

Write a statement that deletes the first two elements from xRow. Ex: [20, 70, 60, 80, 90] becomes [60, 80, 90].

xRow(1:2) = []


Ensembles d'études connexes

Assignment 12 - Single Phase Transformers

View Set

বাংলাদেশের বনভূমি

View Set

aintnoway cuh get me out of here

View Set

Potential Energy & Kinetic Energy 4th Grade Science

View Set

01C - Statistics - Central Tendency, Median

View Set

Chapter 9 & 11: Team Types and Composition

View Set

Chapter 1 Pre & Post Test Questions Oxygen and Medical Gas Therapy

View Set