14-440-127+Lecture+02+Notes

14-440-127+Lecture+02+Notes - 14:440:127— Introduction to...

Info icon This preview shows pages 1–14. Sign up to view the full content.

View Full Document Right Arrow Icon
Image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 2
Image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 4
Image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 6
Image of page 7

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 8
Image of page 9

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 10
Image of page 11

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 12
Image of page 13

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 14
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 14:440:127— Introduction to Computers for Engineers Notes for Lecture 02 Rutgers University, — “ 1 Variables Continued from Lecture 1 1 . 1 Switching Variables Here’s an example of how you need to carefully think through the steps you take when you’re programming. Let’s say we had values stored in the variables a and b. and wanted to switch them. What’s the problem if you type the following?: a = b; b = a; Well, now they both have the value originally stored in b. So how do you perform this switch? Use an intermediate temporary variable: temp = a; 2. store the value of a into temp a = b; 2. overwrite a with the value of b b = temp; X overwrite b with the original a 2 Data Types Unlike a number of popular computer languages, Matlab does not require you to declare variables or their types. I.e. it doesn’t matter if you are going to store an integer, an array of characters, or a decimal number, you can just start using a variable. Matlab is dynamically typed, which means that you can change the type of a variable in the middle of a program without any problems. However, it is strongly typed, which means that it performs checks (and if one type of variable is required for an operation, it won’t work on other types of variables). We’ll see more about data types later in the class. For now, just know that you can type in integers and doubles (essentially, decimals) as numbers. If you want to use alphanumeric text in Matlab, you need to enclose that text in single quotes: i.e. ’my text’. If you don’t enclose the text in single quotes, Matlab will think you are referring to variables. 2.1 NaN, .99999 In Matlab, if you run into NaN, that means ”not a number.” This usually results from trying to perform undefined operations, i.e. dividing O by 0. As you’re working in Matlab, you may also run into some issues where you’ll perform a calculation that should evaluate to 6, but instead it evaluates to 5.99999999999999. The reason for this is that Matlab only performs calculations with a certain degree of precision, and also uses numerical methods to perform calculations. We’ll talk about this in more depth later in the course. 3 Built—In Math Functions Matlab includes many built-in functions for math operations. Here are a number of the most important ones: sqrt(5) Z square root of 5 nthroot(27,3) Zcube(3) root of 27 sin(pi) Z sine of pi radians cos(pi/2) Z cosine of pi/2 asin(1) Z arcsine of 1 sind(75) Z sine of 75 degrees log(5) Z natural logarithm (base e) of 5 log10(5) Z logarithm (base 10) of 5 exp(5) Z e“5 round(5.3) Z round 5.3 (.5 or greater rounds up) fix(5.3) Z round towards O floor(5.3) Z round towards -inf ceil(5.3) Z round towards +inf rem(15,2) Z remainder of 15/2 mod(15,2) Z similar to rem Z but different for different signs Z 1 for x>0, O for x=0, -1 for x<0 sign(x) factor(15) Z returns the prime factors of 15 gcd(15,20) Z the greatest common divisor lcm(3,7) Z least common multiple factorial(15) Z 15! primes(100) Z lists all primes <= 100 isprime(101) Z 1 (true) or 0 (false) 101 is prime 3. 1 Function Examples sqrt(9) Z ans=3 nthroot(81,4) Zans=3 rem(20,3) Z ans = 2 mod(20,3) Z ans = 2 rem(20,-3) Z ans = 2 mod(20,-3) Z ans = -1 primes(10) Z ans = 2 3 5 7 isprime(23549) Z ans 1 round(5.3) Z ans fix(5.3) Z ans = 5 floor(5.3) Z ans = 5 ceil(5.3) Z ans = 6 round(5.6) Z ans = 6 fix(5.6) Z ans = 5 floor(5.6) Z ans = 5 ceil(5.6) Z ans = 6 round(—5.6) Z ans = —6 fix(-5.6) Z ans = -5 floor(-5.6) Z ans = -6 cei1(—5.6) Z ans = -5 3.2 Help If you type help followed by the name of a Matlab command, you’ll get that command’s help file. i.e. help round This is very useful if you want to see how a function works, or what type of input it expects. 4 Comments Whenever you begin a line or part of a line with a percent Sign (%), everything to the right of the percent sign on that line is ignored by Matlab. This is known as a comment. In order to document your Matlab code for yourself and others or remind yourself to do things, you can and should insert comments i.e. stuff = stuff * 10; Z adding a zero Z remember to take the absolute value Comments are also a very useful tool for debugging (fixing problems with) your programs. When you want to eliminate a few lines of code temporarily, you can ”comment them out” rather than cutting and pasting them into and out of your program. 5 Inputs and Outputs 5. 1 Input So far in this class, the main variability in the programs you’ve written has come from you, the programmers, by changing the value of variables you’ve set. In the real world, you’ll usually want to get input from the user, the person who is interacting with your program. For example, if you designed and built an ATM in Matlab, you’d ask the customer how much money they’d like to withdraw. Getting user input in Matlab uses the input function. There are two pieces of information you need to provide along with the input function: what variable to store the information in, as well as What informa— tion should be displayed to the screen in order to prompt the user (give them information about what to enter). Here’s the syntax to store the user’s answer in a variable called money. money = input(’Please enter how much to withdraw: ’); 5.2 Output Formatting- disp, fprintf In the last lecture, we saw the difference between the disp command (just display the value of a variable) and leaving out the semicolon (display the result of the line). disp(:1:) would display: ”5” whereas a: would display ”x = 5” and as; would display nothing at all. For more advanced formatting, you can use the fpm’ntf formatted print function. The fprintf command allows you to specify formatting and also allows you to display values inside other blocks of text. fprintf requires two arguments (input values): 1) a formatting string that details how the formatting works and 2) the variables you want to print, separated by commas The formatting string is contained in single quotes. When you want to reference a variable, you can just say %f (fixed point/decimal), Xe (exponential), ‘7.g (the shorter of decimal and exponential), ‘Zc (a single character), or 2.3 (a string of multiple characters). Realistically, you’ll pretty much always use either %f for numbers or %s for strings. Let’s say you had a variable x that stores a number and a variable name that stores a string of char- acters. If we wanted to print out both in one line, here’s what we could do: name = ’Jones’; X = 14.7; fprintf(’Mr. ZS has Zf Matlab books.\n’, name, x) Notice that the Z3 corresponds to the variable called name and °/.f corresponds to the variable :13. The variables must come in that order! Also, notice the \n at the end of the format string. This means skip to the next line, which Matlab does not do automatically when using fpm‘ntf. In all, this set of commands displays ”Mr. Jones has 14.700000 Matlab books.” What if you want to control finer points about how the text is displayed i.e. how much space is allot- ted or how many digits after the decimal point are shown? Instead of using the ”H” character, you could say something like ”%5.2f”, which still indicates that a floating point (decimal) variable will take its place, but that a width of 5 will be allotted for the variable, and that 2 digits will follow the decimal. Instead, what if you wanted to just indicate that the number should be displayed as an integer? This is equivalent to saying that 0 digits should be used after the decimal: name = ’Jones’; x = 14.7; fprinth’Mr. %s has 7..0f Matlab books.\n’, name, x) This would display ”Mr. Jones has 15 Matlab books.” Note that if you use a format string and then have a veCtor or matrix stored in the corresponding vari- able, Matlab will effectively repeat the format string for each value in the vector or matrix. 6 True And False In just about all computer languages, you’ll run into the concept of TRUE and FALSE. A statement can be True ( i.e. 5 > 3 ), or a statement can be False ( i.e. 5 < 3 ). In Matlab and basically all programming languages, 0 means False 1, and any other number besides 0, mean True For instance, if you typed in 5 > 3, Matlab would display ans 2 1 because 5 > 3 is a True statement. 6.1 Relational Operators Relational operators are the tests you can use to compare the relationships between two quantities (numbers, variables, etc): > is it greater than? < is it less than? is it greater than or equal to? is it less than or equal to? (2 equals signs!) is it equal to? is it NOT equal to? IMPORTANT: If you only have a single equal sign, you’re not comparing two numbers, you’re setting a variable! Therefore, to test (True/ False) whether X equals 15, you’d say 15::15 6.2 LOGI'CAL OPERATORS Sometimes, you want to test the truth of multiple statements at once. You can do this using logical operators: & means AND--- both true If both statements are true, then the result is true. Otherwise, the result is false. X> 5eX> 10 is’I‘rue(1)0nlyifBOTHX>5ANDX>10 | means 0R--- either true If there is a true statement anywhere (the first statement is true, the second statement is true, or both statements are true), then the result is true. X > 5 | X > 10 is True (1) if X > 5 OR if X < -10. If either one of those statements is true, the whole statement is true. ” means NOT——— switches True and False If the statement was originally true, applying NOT (") makes the result false, and vice versa. ”(X==1S)is True (1) when X equals any number except 15. 7 Conditional Statements A very important part of computer programming is the ability to make decisions based on whether things are True or False. To do this, you’ll use ‘If Statements,’ which are a crucial part of just about every programming language. 7.1 If Statement In Matlab, If Statements are implemented as follows, replacing CONDITION with an expression that eval- uates to True or False: if(CONDITION) MATLAB STATEMENTS end As an example, let’s consider: if (ranking <= 8) disp(’Your team made the playoffs’) end In this example, if the variable ranking contains the value 8 or lower, then Matlab will display ‘Your team made the playoffs.’ If ranking is larger than 8, then Matlab doesn’t do anything! In essence, Matlab will only do something (execute the indicated statements) IF the condition is true. 7.2 If—Else Statements Sometimes, you’ll want to take one action if the condition is true and a different action if the condition is false. Matlab lets you use If—Else Statements to say ”If the condition is true, let’s do only the first set of actions; however, if the condition is false, let’s execute only the second set of actions.” if(CONDITION) MATLAB STATEMENTS else MATLAB STATEMENTS end As an example, let’s consider: if (ranking <= 8) . disp(’Your team made the playoffs’) else disp(’You did not make the playoffs. Sucks.’ end In this example, if the variable ranking contains a number less than or equal to 8, then Matlab will display ‘Your team made the playoffs’. If ranking is greater than 8, then Matlab displays ‘You did not make the playoffs. Sucks.’ Notice that only one of the actions is taken, not both. 7.3 If—Elseif—...-Else Statements Sometimes, you’ll want your program to choose one from many courses of action. In these instances, use If—Elseif—Else statements. if(condition) statementsl elseif(condition2) statements2 else statementsB end Matlab Will first evaluate the truth of the If condition. If that condition is true, it executes statementsl and then skips down to the end. If that first condition is not true, but condition2 is indeed true, Matlab executes only statements2 and then skips down to the end. If Matlab goes through the if condition and all of the el- sez'f conditions and hasn’t found anything that’s true, it will execute the statements under else (statements3). Note that you can have as many elsez'f statements as you want. Furthermore, the else statement is op— tional. Most importantly, only the statements from ONE condition will ever execute, no matter how many conditions are true. Only the statements with the FIRST true condition will execute. As an example, let’s consider the following example that splits people by their age: if(age>=65) disp(’You are a senior citizen’) elseif(age>=25) disp(’You are a grown-up’) elseif(age>=18) disp(’You are a college student’) e1seif(age>=5) disp(’You are in school’) else disp(’You are a little kid’); end It’s important to note in this example that only one of these options is chosen. In essence, beginning at the if and going all the way to end statement, the first true condition will have its statement(s) executed, and all of the others will be ignored. As a result, the order of the statements matters very much! What would happen if the first statement in the example above were if(age>=5)? Well, it would display ’You are in school’ for everyone over age 5, overriding the messages about senior citizens, grown-ups, and college students. 7.4 More examples of Conditionals This first example uses the OR operator extensively. Think about what would have happened if the order were changed (i.e. if the second condition came before the first). x = input(’enter an integer: ’); if(x>=1000 I x<='1000) disp(’number has 4+ digits’) elseif(x>=100 | x<=-100) disp(’number has 3 digits’) elseif(x>=10 | x<=-10) dispC’number has 2 digits’) elseif(x==0) disp(’number is 0’) else disp(’number has 1 digit’); end However, there’s a shorter way to solve the above problem, creatively using the functions you learned earlier in this lecture. x input(’enter an integer: ’); x abs(x); Z makes x positive if(x==0) fprintf(’number is O\n’) else d = floor(log10(x))+1; Z calculate the log, base 10 Z round down, and add 1 (so that powers of 10 work correctly) fprintf(’number has Z.Of digits before the decimal\n’,d) end if(grade>100 I grade<0) disp(’Did you enter the grade correctly?’); elseif(grade>70) disp(’You passed’) else disp(’You failed’); end This next example shows the AND operator in action: if(age>=17 & age<=25) disp(’You can drive, but can”t rent a car’); end Notice in this example that we typed two single quotes inside of a string of characters. Normally, the single quote ends the string, but two single quotes right next to each other lets you include the apostrophe inside the string. This example shows both the AND as well as the OR operators in action. Let’s assume the variable beendr’inking contains a 1 (true) if the driver has been drinking, and a 0 otherwise. Similarly, let’s assume the variable Dumb contains a 1 if the driver just doesn’t care about reason or drunk driving laws. If the driver is 17 or older and sober, OR if he is Dumb, he will drive: if( (age>=17 & beendrinking==0) I Dumb==1 ) disp(’He is going to drive’); end Note that there are many ways to write the above statement. For instance, saying Dumb==1 is superfluous. You could have merely said Dumb, which would have evaluated to False if it contained 0 (false), and evaluated to True if it contained 1 (true). Similarly, you could have just typed ~beendrinking.... ”not beendrinking”. If beendrinking were 0, ”beendrinking would have been true. So for an adult, age>=17 and ”beendrinking would have both evaluated to true, and thus that whole statement would have been true. 7.5 Switch/Case Switch case (sometimes known as select case) is an alternative to If Statements when you have a variable that only takes on a certain number of discrete values. In all honesty, you never need to use a switch case statement if you know if statements well, but you should recognize the statement when reading other pro- grammers’ code. In particular, it’s usually easier to read a switch case statement than an if statement if you’re dealing with character strings. The syntax is as follows: switch VARIABLE case OPTIONl STATEMENTS case DPTIONQ STATEMENTS otherwise STATEMENTS end You must replace ‘VARIABLE’ with the name of the variable you wish to test. Replace OPTIONl, OP— TION2, etc. with values (you don’t need to put x==5, you JUST type 5). If you want to include more than one value, put all of the possibilities in squigly braces! Matlab will look up the value of the variable that follows the word ‘switch,’ and go down the list of possible cases until it finds one that is true (and executes the corresponding statements). Once it, finds one that is true, it doesn’t even look at any of the others. The optional ‘OTHERWISE’ statement is entirely equivalent to ‘else’ in an if statement— if you get down to the otherwise statement, you will execute those statements. Here’s an example of switch case in action. Note that ‘exciting’ will be displayed: destination= ’bolivia’; switch destination case ’florida’ disp(’boring!’) case ’italy’ disp(’a little less boring’) case {’peru’ , ’bolivia’ } disp(’exciting’) otherwise disp(’i don”t know about that country’) end 8 Vectors and Matrices 8.1 Creating Vectors or Matrices Creating matrices or vectors (matrices with only 1 row OR 1 column) is quite easy in Matlab. You simply enclose a list of elements in square brackets. Here’s our first row vector (1 row, 4 columns): To instead create column vectors, you need to indicate to Matlab to ”skip to the next row” in the vector. You use the semicolon ( ; ) to do this: y=[1;5;8;9] As you might guess, creating a Matrix is essentially the same as a vector. Don’t forget that the semi— colon skips to the next row: z=[123;456] This creates a 2x3 (2 rows by 3 columns) Matrix. Whenever we talk about the size of Matrices, the number of rows always comes first. 8.2 Special Ways to Create Vectors/ Matrices Matlab presents a number of more efficient ways to create certain types of vectors and matrices. 8.2.1 Colon For cases where you need to create a vector of, say, the integers from 1 to 1000, you can do so by using the colon operator, which in Matlab essentially means ”from X to Y” when you write XzY. a= 1:1000 The code above creates the vector [1 2 3 1000], containing all of the integers from 1 to 1,000. By default, the colon uses steps of 1 when going from one number to the next. By adding an operator in the middle that specifies the ”step,” AKA ”how much to skip by” when going between points, you can change this default. You’ll want to do this when trying to space points very close together, or decreasing between points rather than increasing: Z variable = start : skip : end 1:0.1:1000 b = O:-1:-100 The ”a:” line above creates a vector containing [1 1.1 1.2 1.3... 999.8 999.9 1000], the numbers from 1 to 1,000 skipping by 0.1. Similarly, the ”b:” line above creates a vector starting at 0 and going down (skipping by —1 each time) to —100: [0 -1 -2 —99 -100]. 8.2.2 Linspace Whereas the colon operator is very useful for creating vectors when you know how much space to skip in between each point, sometimes you’ll want to say something like, ‘give me 200 points between 5 and 22.’ To accomplish this task, you use the linspace operator, which spaces points evenly (the points are linear) between a start number and end number: 7. variable = linspace(start,stop,# of points) c = linspace(5,22,200) This example creates a vector of 200 evenly spaced points, beginning at 5 and ending at 22. 8.2.3 From Other Matrices When creating a Matrix using the square brackets ( [ ] ), other vectors or matrices can be included inside the brackets. For instance, given a vector c : [ 1 2 5’ ], you could write d = [ c ,' c ], and you’d get d equal to the following 2x3 vector: Note that this isn’t a matrix with other matrices inside of it, but rather one big matrix of numbers. 8.2.4 Ones, Zeros, Eye Three functions exist to quickly create special matrices: 0nes(3,4) creates a 3x4 matrix filled entirely with the number 1. If you only pass the ones function a single parameter i.e. 0nes(3), a 3x3 square matrix filled with the number 1 is created. If you multiply the matrix created by ones by a scalar (single) number, you can now ...
View Full Document

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern