MATLAB Basic Programming

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What is the only character that indicates a comment?

%

Complete the statement to obtain a string from the user rather than a number. userName = input('Sally', ______________ );

's' 's' causes the user's input to be read in as a character vector -- even if the user enters a number.

x * y * z

(x * y) * z

x / 2 + y / 2

(x / 2) + (y / 2)

z / 2-x

(z / 2) - x

Complex numbers. Assume i and j are the predefined values for the imaginary component of an imaginary number. 1) What is the result of numA = i * i?

-1

Whats another way to do this?

0:1:11

Whats another way to do this?

0:1:2

What happens to input and output variables in a function call? 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 1) What is the value of inVar in the global workspace after executing: inVar = 1; out1 = PlusOne(inVar);

1

Which are valid identifiers? 1) r2d2 2) name$ 3) _2a 4) pay_day 5) pay-day 6) 2a 7) y____5 8) switch

1, 4 and 7

Multiple statements on a line. 1) What is val after executing the line num = 6; num = num * 2; val = num + 1;

13 num will assigned with 6 * 2 or 12. Then val will be assigned with 12 + 1 or 13.

What is totCount after executing the following? numItems = 5; totCount = 1 + (2 * numItems) * 4;

44 After (2 * 5) is evaluated, * 4 is evaluated because * has precedence over +

What is x after executing the line x = 5; y = 9; y = x; x = y;

5

What is the next value after 34 in the Fibonacci rabbits example?

55

Assume apples currently has the value 5 and oranges the value 9. What is the value stored in apples after the following statement? apples = apples + 1;

6 5 + 1 yields 6

Assume that no variables have been assigned yet in the workspace. How many variables would be assigned after executing the following code: distancePes = 1000; timeSecundae = 55; RomanUnitsToMPH

8

If the previously-entered statement was "num1 = 9", what value will be stored in num2 after the statement "num2 = num1 * num1"?

81

Assume apples currently has the value 5 and oranges the value 9. What is the value stored in apples after the following statements? apples = oranges; oranges = oranges + 1;

9

What is the decimal number stored in a char variable delimChar after the following statement: delimChar = 'a';

97

What symbol at the end of a statement suppresses printing of the result?

; (semicolon)

How would you clean up this plot?

By plotting axis label and a title; the text inside the single quotes is a string which we intend to be the labels. xlabel('u'); ylabel('v'); title('v = cos(u)'); command "help plot" would be very helpful

Does 2 ^ 3 ^ 2 equal 64?

Correct The power operators evaluate left to right, so (2^3)^2 or 8^2, which is 64.

Does -4 ^ 2 equal -16?

Correct ^ has higher precedence than -, so -(4^2) is -(16).

Given the following script saved in file CostDrive.m: miles = 100; costPerMile = 0.30; cost = miles * costPerMile; What is the command line statement to run the script?

CostDrive (with .m omitted)

Does 2 + 3 * 4 - 4 equal 16?

Incorrect * has higher precedence, so 2 + 12 - 4 is 10.

Evaluating expressions using precedence rules. Note: This activity omits parentheses to test knowledge of precedence rules. But programmers should use parentheses to make evaluation order explicit. 1) Does 2 / 2 * 3 equal 2/6?

Incorrect / and * have equal precedence so are evaluated left to right, thus (2/2)*3, which is 1*3, yielding 3.

Does 2 / 3 ^2 equal 4/9?

Incorrect Exponent has higher precedence, so 2/(3^2) is 2/9.

Complete the statement that prompts the user with 'Enter your age: ' and assigns the variable userAge with the user-entered value.

userAge = input('Enter your age: ')

Using notation similar to 6.02e23 and starting with 3.1, write a statement to assign variable wrenchTorque with the value 3,125.99.

wrenchTorque = 3.12599e3;

x + 1 * y / 2

x + ((1 * y) / 2)

x + y ^ 3

x + (y ^ 3)

Write a statement that would transpose a 3x4 matrix

x = [1 2 3 4; 5 6 7 8; 9 10 11 12]; x' x = 1 2 3 4 5 6 7 8 9 10 11 12 ans = 1 5 9 2 6 10 3 7 11 4 8 12

Now Suppose you want to automatically generate a vector of 11 entries; the 1st entry starting at 0 and ends at 1. How would you create this vector in MATLAB?

x = linspace(0,1,11)

Suppose you want to automatically generate a vector of with 2 entries; the 1st entry starting at 0 and ends at 1. How would you create this vector in MATLAB?

x = linspace(0,1,2)

Now Suppose you want to automatically generate a vector with 8 entries; the 1st entry starting at 0 and ends at 3. How would you create this vector in MATLAB?

x = linspace(0,3,8) or x = 0:3:8

Given x='a'; y='b', assign x with the current value of y. End with a semicolon.

x = y;

>> tempVal = x; >> x = y; >> y = tempVal; x is 99 and y is 22. x is 99 and y is 99.

x is 99 and y is 22.

>> tempVal = x; >> x = y; >> y = x; x is 99 and y is 22. x is 99 and y is 99.

x is 99 and y is 99.

>> x = y; >> y = x; >> x = y; x is 99 and y is 22. x is 99 and y is 99. x is 22 and y is 22.

x is 99 and y is 99.

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

x is 99 and y is 99.

Write a statement transposing x

x'

Matlab challenge activities Multiply x by 2 and put the result in y. Ex: If x is 2, then output y should be 4.

x=2; y=x+2

Precedence rules. Select the expression whose parentheses enforce the compiler's evaluation order for the original expression. Note: Using such parentheses is preferable over relying on precedence rules. y + 2 * z

y + (2 * z)

How would you access the first twelve elements for y?

y = (1:12); x(1:12) OR y = (1:12); x(1:12)

MATLAB makes it easy to manipulate audio signals. A harmonic signal, which is a signal with one frequency (a "pure tone"), can be expressed in MATLAB code as

y = A * sin( 2 * pi * f * t) where f is the frequency in Hz, t is a row array of time points (corresponding to the sample time instances), and A is the amplitude.

How would you access the 1st four multiples of 3 specified in a vector?

y([3 6 9 12])

Write two statements that notes the difference in tranpose of z

z' and z.'

A bit is a 0 or 1, interpreted from voltage. True False

true 1 is usually a higher voltage (e.g., 2.0 V), 0 is usually a lower voltage (e.g., 0 V).

String scalars and character vectors. 1) Assign variable unitName with character vector: miles

unitName = 'miles';

Assign variable unitName with string scalar: nautical miles

unitName = 'nautical miles';

Assign variable phrase with string scalar: Isn't it OK?

"Isn't it OK?"

If the previously-entered statement was "num1 = 5", what value will be stored in num2 after the statements "num1 = num1 + num1" followed by "num2 = num1 + 3".

13;; The interpreter computes 5 + 5, which is 10, then stores 10 in num1. The interpreter then computes num1 + 3, which is 10 + 3 or 13, and stores 13 in num2.

Suppose distanceMiles equals 1870, timeSecs equals 343440, and speedMPH equals 55.0. What is the value of speedMPH after calling CalculateMPH?

19.6

What is the value of inVar in the global workspace after executing: inVar = 1; inVar = PlusOne(inVar);

2

Mathematical constants. Which of the following variables are predefined mathematical constants? 1) Eps 2) J 3) NaN 4) e 5) inf

3

Repeated commands. 1) Variable num is initially 2. The command num = num * 2 is typed and entered once; then the up-arrow key is pressed followed by enter, three times. What is num?

32 num = num * 2 is executed four times, leading to 2*2 or 4, then 4*2 or 8, then 8*2 or 16, and finally 16*2 or 32.

What will the statement "myNum = 2 + 2" store in myNum?

4

What is the value stored in luckyNumber after these two statements execute? luckyNumber = 7; luckyNumber = 4;

4 The second write to luckyNumber overwrites the first value written into the variable.

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 The code is correct as is. Matt should use "A = 6, B = 9; C = A + B" instead. Matt should use "A =6; B = 9, C = A + B;" instead.

Matt should use "A = 6, B = 9; C = A + B" instead.

Test your understanding of what will be output to the command window as a result of entering the following lines. 1) X = 14; Y = 2, Z = 5 Only X will display. Only Y and Z will display. None of the above.

Only Y and Z will display. The semicolon suppresses the output of X, commas do not suppress output.

C = 100 K = C + 273 Only C will display. Both C and K will display. The statement results in an error.

Statements must be separated by a semicolon or comma, else the line is treated as one statement, which in this case is not a valid statement, yielding an error.

Expression with multiple exponents: Computing wind chill Wind chill (C) is computed from the air temperature (T) and wind speed (W): C = 35.7 + 0.6T - 35.7W^0.16 + 0.43TW^0.16 Write a statement that assigns windChill (C) with the wind chill given airTemp (T) and windSpeed (W). Ex: If airTemp is 32 and windSpeed is 10, then windChill is assigned with 23.1871.

airTemp = 32; windSpeed = 10; % Assigns windChill with the temperature felt given airTemp and windSpeed windChill = 35.7 + 0.6*(32) - 35.7*(10)^0.16 + 0.43*(32)*(10)^0.16

Assign variable allowBoat with character vector: OK'ed

allowBoat = 'OK''ed';

Write two statements, the first setting apples to 7, and the second setting oranges to apples plus one. Terminate each statement with a semicolon.

apples = 7; oranges = apples + 1; "apples = 7" must be done first, then "oranges = apples + 1" will store 7+1 or 8 into oranges

Write a statement, ending with "- 1;", that decreases the value stored in apples by 1.

apples = apples - 1;

Write a variable assignment statement that assigns birdFeeders with the current value of variable stockCount, and prints the value of the variable to the command window.

birdFeeders = stockCount

Assign celsiusVal with kelvinVal minus 273.15.

celsiusVal = kelvinVal - 273.15;

Write a statement that assigns circleArea with the circle's area given circleRadius

circleRadius = 5 % Modify to use built-in math constant pi. circleArea = pi*circleRadius*circleRadius

Characters. 1) Write a statement that assigns variable delimChar with the comma character. End with a semicolon.

delimChar = ', ';

Unformatted output. Write a statement using the disp function. End with a semicolon. 1) Output the value of a variable named distance.

disp(distance);

Assume that no variables have been assigned yet in the workspace. What statement would calculate the speed in miles per hour for a distance of 56.9 miles and elapsed time of 73 minutes?

distanceMiles = 56.9; timeSecs = 73*60; CalculateMPH

If all previous statements dealt only with num1, num2, and num3, what value will the statement "num4" print?

error

What are the entries in linspace to create an array of 100,000 elements to create a linearly increasing fade in?

fadeIn = linspace(0,1,100000)

What are the entries in linspace to create a row array of 100,000 elements that creates a linearly decreasing fade out?

fadeOut = linspace(1,0,100000)

A double-precision number's range is about 10 times greater than a single-precision number's range. True False

false

A memory is a circuit that stores one machine instruction. True False

false

The smallest positive number that the default MATLAB floating-point representation can store is 1.1755e-38 True False

false

The statement "myInt = 44" creates an integer variable. True False

false

The statement "myNum = 0.1" creates a single-precision floating-point number because 0.1 is small enough for single precision. True False

false

Write a statement that assigns finalResult with firstSample plus secondSample, divided by 3. Ex: If firstSample is 18 and secondSample is 12, finalResult is 10.

finalResult = (1/3) * (firstSample + secondSample)

Format operator %f for floating-point output. 1) Type the formatting operator. numMeters is a floating-point variable.

fprintf('Meters: %f', numMeters);

Function definition: Double down Complete the DoubleDown function to return twice the initialValue.

function finalValue = DoubleDown( initialValue ) % Complete the function to return twice the initialValue finalValue = 2*initialValue end DoubleDown(5) % Change the input to DoubleDown to test other values

Function definition: Volume of a pyramid Define a function CalculatePyramidVolume with inputs baseLength, baseWidth, and pyramidHeight. The function returns pyramidVolume, the volume of a pyramid with a rectangular base. Hint: Recall that a function declaration begins with 'function'. Pay attention to the spelling and character case of variables. Ex: pyramidvalue and pyramidValue are different variables. Relevant geometry equation: pyramidVolume = baseLength * baseWidth * pyramidHeight * 1/3 Ex: CalculatePyramidVolume(1, 1, 1) returns ans = 0.3333

function pyramidVolume = CalculatePyramidVolume(baseLength, baseWidth, pyramidHeight) pyramidVolume = baseLength * baseWidth * pyramidHeight * (1/3) end %function declaration

Function call in expression: Reduced pricing Write a single statement that assigns totalCost with the discounted cost of item 1 and item 2. Use the provided function DiscountedPrice to determine the discounted cost of each item:

function totalCost = CartTotal(item1Cost, item1Discount, item2Cost, item2Discount) % Assign totalCost with the discounted cost of items 1 and 2 totalCost = DiscountedPrice(item1Cost, item1Discount) + DiscountedPrice(item2Cost, item2Discount) end

Assign y with 5 plus x. Ex: If x is 2, then y is 7. If x is 19, then y is 24.

function y = IncreaseValue(x) % x: User defined value that is added to 5 % Modify the line below to y = 5 + x y = 5 + x; end Code to call your function : IncreaseValue(2)

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

function yVal = CubeNum (xVal)

Write a statement that assigns the logical variable isAvailable with the logical value 'true'.

isAvailable = true

Write a variable assignment statement that assigns luckyNumber with 7 and suppresses the output to the command window.

luckyNumber = 7;

Declaring a character Write a statement that assigns middleInitial with the character T.

myChar = 'T'; middleInitial = myChar

% Write a statement that assigns myCurvedExamScore with myExamScore + 5

myCurvedExamScore = myExamScore + 5

% Write a statement that assigns myExamScore with 82

myExamScore = 82

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

myNum = CalcR(3, 9)

Elementary functions in MATLAB Use the following few commands (a script) to make a plot. The evaluation of v=cos(u) creates a vector whose elements are: v(k) = cos(u(k)) where k = 1, 2, ...n

n = anu number; u = linspace(0, 2*pi*n); v = cos(u); plot(u,v)

What are the entries in linspace to create a row array of 300,000 elements all equal to 1?

normalVol = linspace(1,1,300000)

What will the command window display after the assignment numB = 4.5 + 2*i?

numB = 4.5000 + 2.0000i

What will the command window display after the assignment numC = 3.2 + 5*j?

numC = 3.2000 + 5.0000i

numNickels = 5 numDimes = 10 % Write a statement that assigns numCoins with numNickels + numDimes

numCoins = numNickels + numDimes

Rewrite the following expression without using the * symbol: numD = 7 + 5*j;

numD = 7+5j;

A drink costs 2 dollars. A taco costs 3 dollars. Write a statement that assigns totalCost with the total meal cost given the number of drinks and tacos. Ex: 4 drinks and 6 tacos yields totalCost of 26.

numDrinks = 4 % Number of drinks numTacos = 6 % Number of tacos % assigns totalCost with the total meal cost given the number of drinks and tacos totalCost = (2*4) + (6*3)

Rewrite the following expression without using i: numE = 3 + 6i;

numE = 3 + 6j

X = 39; Y = 41, Z = X + 17 The statement results in an error. Only Y is displayed. Only Y and Z are displayed.

only Y and Z displayed

Use concatenation to create the array profileSound that contains fadeIn, normalVol, and fadeOut.

profileSound = [fadeIn, normalVol, fadeOut];

Provide the code to play the sound clip ySound (1:500000) with the audio volume profile described in profileSound.

sound(ySound (1:500000) .* profileSound', sampleFreq);

Suppress the output of all assignment statements. 1) Write a statement that assigns the double precision floating-point variable tempKelvin with 0.0.

tempKelvin = 0.0;

Given a Fahrenheit value temperatureFahrenheit, write a statement that assigns temperatureCelsius with the equivalent Celsius value. While the equation is C = 5/9 * (F - 32), as an exercise use two statements, the first of which is "fractionalMultiplier = 5/9;". 77 degrees fahrenheit % Write a statement that assigns fractionalMultiplier with 5/9 % Modify the statement below to convert Fahrenheit to Celsius, % assigning temperatureCelsius with the Celsius value

temperatureCelsius = (5/9) * (77 - 32) = 25

The command sound(ySound,Fs) plays

the sound stored in array ySound using sampling frequency Fs.

Defining numeric variables. 1) Write a variable assignment statement that assigns totalPets with 3.

totalPets = 3; or totalPets = 3

A high-level language eases a programmer's task of writing complex programs.

true

A processor is a circuit that executes instructions. True False

true

An assembler translates an assembly program into machine instructions. True False

true

The default MATLAB floating-point representation can represent various numbers from -1.79e+308 to +1.79e+308.

true


संबंधित स्टडी सेट्स

Unit 2 progress check: MCQ part A, Unit 2 progress check: MCQ part B, AP GOV MCQ unit 2

View Set

How to conduct a Command Climate Assessment and Administer the Defense Organizational Climate Survey

View Set

Chapter 5 Life Insurance Questions

View Set