midterm lectures 1-10 for …math.hawaii.edu/~dale/190/midterm-lectures.pdf ·  ·...

46
Midterm Lectures 1-10 Lecture 1 arithmetic and functions MATH 190 WEBSITE: math.hawaii.edu/190 Open this in Chrome (not Firefox ). Read and accept the Terms of Acceptable Lab Use. Open Lecture 1. Open Scilab. On the sign-up sheet, print and sign your name. Record your computer name, login name and password. PREREQUISITE: You must have taken or be taking Calculus I concurrently. If not taken here, specify the college and course title/number. Otherwise, you must drop. If you don’t need Matlab or Fortran, you should take an ICS class instead. MATLAB (SCILAB) AND FORTRAN Javascript programs webpages. Perl, Python, PHP program webservers. Large team-programming projects use C++ or Java . Fortran (engineering math) and C are used when supercomputer speed is needed. Mathematica, Maple and Matlab (engineering) are used for symbolic math (handling formulas rather than numbers). This course teaches Matlab (first five weeks: lots of built-in apps, slow, hard to program) and Fortran (last 10 weeks: easy to program, very fast). They have the biggest engineering program libraries. On your home computer (1) install a free version of Matlab (Scilab) and (2) a compiler (g95.exe or gfortran) and editor (SciTE) for Fortran. Go to the class website (www.math.hawaii.edu/190) for instructions on both Scilab and Fortran. Have Scilab, Fortran and SciTE up and running by the next week (if you can’t get some fortran installed, this course will be a little hard). ARITHMETIC +, *, /, ^ Double-click the Scilab icon (top center, black with red dots). Enter the following: (active participation is required) 3+2 3*2 3/2 3^2 3**2 Use ^ or ** for exponentiation. VARIABLES Variables are locations in memory. a variables must be initialized a = 2 a=2 spaces don’t matter a A Matlab is case sensitive, Fortran is not. b=3 a+b ab ab is two-letter variable name, it is not a*b a*b must use * for products cost=1000*(1.05)^8 cost is a variable just like a, b, c Start a variable name with a letter followed optionally with letters, digits or the underscore: a12 (for ), vol_box. a 12 CONSTANTS AND BUILT-IN FUNCTIONS on Thursday's quiz x=100 100 a constant.

Upload: votu

Post on 11-Apr-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

Midterm Lectures 1-10Lecture 1 arithmetic and functions

MATH 190 WEBSITE: math.hawaii.edu/190 Open this inChrome (not Firefox). Read and accept the Terms ofAcceptable Lab Use. Open Lecture 1. Open Scilab.

On the sign-up sheet, print and sign your name. Recordyour computer name, login name and password.

PREREQUISITE: You must have taken or be taking Calculus Iconcurrently. If not taken here, specify the college andcourse title/number. Otherwise, you must drop. If you don’tneed Matlab or Fortran, you should take an ICS class instead.

MATLAB (SCILAB) AND FORTRAN Javascript programs webpages. Perl, Python, PHP program webservers. Large team-programming projects use C++ or Java . Fortran (engineering math) and C are used when

supercomputer speed is needed. Mathematica, Maple and Matlab (engineering) are used for

symbolic math (handling formulas rather than numbers).

This course teaches Matlab (first five weeks: lots of built-in

apps, slow, hard to program) and Fortran (last 10 weeks: easy to

program, very fast). They have the biggest engineering programlibraries. On your home computer (1) install a free version ofMatlab (Scilab) and (2) a compiler (g95.exe or gfortran) andeditor (SciTE) for Fortran. Go to the class website

(www.math.hawaii.edu/190) for instructions on both Scilaband Fortran. Have Scilab, Fortran and SciTE up and runningby the next week (if you can’t get some fortran installed, this course

will be a little hard).

ARITHMETIC +, *, /, ^Double-click the Scilab icon (top center, black with red dots).

Enter the following: (active participation is required)3+2 3*2 3/2 3^2 3**2 Use ^ or ** for exponentiation.

VARIABLES Variables are locations in memory. a variables must be initialized a = 2 a=2 spaces don’t matter a A Matlab is case sensitive, Fortran is not. b=3 a+b ab ab is two-letter variable name, it is not a*ba*b must use * for products cost=1000*(1.05)^8

cost is a variable just like a, b, c Start a variable name with a letter followed optionally withletters, digits or the underscore: a12 (for ), vol_box.a12

CONSTANTS AND BUILT-IN FUNCTIONS on Thursday's quizx=100 100 a constant.

%pi = = 3.14 ... %e =2.716 ... log(x) =ln(x), the natural logarithm log10(x) common base-10 logarithm sqrt(4) 4abs(-3) absolute value |-3| round(4.5) rounds to the nearest integer (5 in this case). ceil(4.5) rounds up to nearest >= integer. >= means > floor(4.5) rounds down to nearest <= integer. <= means < floor(13/5) quotient of 13/5modulo(13,5) remainder of 13/5 factorial(3) = 3! = 3*2*1 sin(%pi/2) angles are in radians, not degrees sin, cos, tan are the trig functions in radians. asin, acos, atan are the inverse trig functions: arcsin,arccos, arctan, i.e., sin1, cos1, tan1

rand() returns a random number between 0 and 1

ASSIGNMENT COMMMAND AND EQUALITY TESTS. x=a,x==aIn math, is the statement “x equals 2”. In Matlab, x 2

is the assignment command “set x equal to 2” (anyx 2earlier value is lost).

To test if x equals 2 in Matlab, write “x==1 ”. x variables must be initialized x=2 x= =2 T = "True" x= =0 F = "False" x= =x+1 is always false. x=x+1 new value on left, old on the right - increments x x+1=x wrong, need variable on the left, formula on right x=input('Enter a number. > ') gets x from keyboard

x<=3 test if x 3x>=3 test if x 3x~=3 test if (x/=3 in Fortran, x!=3 in PHP, C)x 3

COMMENTS // In Scilab // indicates a comment (which the computer ignores).

Which of the next two lines gives an error? log(%e) natural logarithm log(%e) //natural logarithm

PRINTING

clc clears the console window, i.e. Scilab windowdisp(...) displays a value on the console windowdisp("a",b,1) displays letter a, value of b, 1 in reverse order.printf("...",...) prints a formatted line on the console printf("\n") prints a blank line "\n" is the new line character

ALL VARIABLES ARE INDEPENDENT

A variable is a memory location in the computer. x=y copies the value at location y to location x. x=2 f=2*x x=3 f changing x doesn’t change the value in memory location f

Matlab variables are independent (they don’t depend on other

variables). To make f a dependent variable that depends on x,define it as a function f(x). rather than .f x 2x y 2x

FUNCTIONS on Thursday's quiz is the formula for the area of a circle of radius r. r2

%pi*r^2 is the Scilab version. is a function whose value is the area of the circle.Ar r2

The Scilab version of this function is --EXAMPLE E1.1 area_circle Write a function area_circle(r)for the area of a circle of radius r. Find the area of a circle ofradius 10.

function A=area_circle(r)A=%pi*r^2

endfunction disp(area_circle(10))

area_circle is the function name. A is the outputvariable, it must be set to the function’s value. To call thefunction, use the name area_circle(10) . (Don’t use the output

variable A, it is not visible outside the function). After the function,display some value in the Scilab window with a testing line,e.g., disp(area_circle(10)). Scilab doesn’t need testinglines, we do to see if the function works. (If you don’t seeanything, you probably forgot the testing line.)

The volume of a sphere of radius r is . 4r3

3The Scilab formula is 4*%pi*r^3/3.

FOR LOOPSfor i=1:10 disp(i) //displays i for each i from i=1 to i=10end

CONDITIONALS

if x<1 then //then must be on same line as if printf("x is less than 1") elseif x==1 then printf("x equals 1")else //what to do if none of the above are true printf("x more than than 1")end

CLASSWORK C1.1(2) vol_sphere Together. Write a functionvol_sphere(r) which gives the volume of a sphere ofradius r. Always include a testing line.

//c1.1(2)vol_sphere test on 6.function V=vol_sphere(r) //delete this line, assign V to the volume formula.endfunction disp(vol_sphere(6)) //displayed answer = 904.77868

The last line tests the function on 6.

Write functions in SciNotes, not in Scilab. Click Applications/SciNotes to open SciNotes. Copy/paste the above code lines (from Chrome, not Firefox). Highlight/copy the file name c1.1(3)vol_sphereFile/Save as c1.1(3)vol_sphere, save in drive H: If you don’t see H:, click the directory drop-down menu.Write the function-value assignment where the pink line is. Press < F5> or Select Execute...file with no echo . The answer 904.77868 appears in the Scilab window.

Once a function has been executed, it may be used inScilab. Go to the Scilab window and enter

vol_sphere(10) //should get 4188.7902

For cleaner output, add “clc” below the endfunctionline. Press < F2> to clear Scilab’s console window. To enable/disable auto-completion in SciNotes, click“Preferences” and check/uncheck both “Auto completion”lines. Play with settings, see what happens.

In SciNotes, <tab> moves forward one indent, <shift-tab>moves backwards one indent. CLASSWORK C1.2(4) even_odd. Together. Write a functioneven_odd(n) which returns negative if n is negative,else returns even if n is even, odd otherwise. Test it on n =-1,0,1, ..., 9. Make the formatted printout look like

-1 is negative 0 is even 1 is odd 2 is even... 9 is oddCopy lines, File/New in SciNotes, paste, File/Save as c1.2(4)even_odd 3

//c1.2(4)even_odd test on 0,1,...,9.//delete this line, define the function here, need 7 lines.

clc;printf("\n") //clear console; print blank linefor n=-1:9 //last 4 lines not on next quiz printf(" %i is %s \n",n, even_odd(n))end

Leave the previous SciNotes window open.Select File/New (or <ctrl-n>). Copy/paste the given code lines to the new window.File/Save as c1.2(3)even_odd, save in drive H: Replace the pink line with the needed function lines. Select Execute ... file with no echo or < F5>.

CLASSWORK PROBLEMS DUE AT THE END OF EACH CLASS

C1.1(2)vol_sphere, C1.2(4)even_odd email to:[email protected] subject line: 190 c1(6)

vOpen/write/compose a new email message. Open a browser-based email client. E.g. Gmail, Hotmail, Yahoo or clickthe UH Webmail link on our class website, or go to your MyUHaccount.

v Copy/paste [email protected] as the "To:" address.v Copy/paste the subject line exactly. v Copy/paste each classwork problem from SciNotes (neverfrom Scilab) into the message body:

highlight the lines to be copied or press <ctrl-a>, press <ctrl-c> or select edit/copy, put the cursor in the email message, press <ctrl-v> or select edit/paste.

Add two blank lines after each problem including the last.Check: Copy<ctrl-c>/paste<ctrl-v> each email probleminto Scilab and press enter. Send the email.

Don’t attach files (attachments get scrubbed).

Do not add anything else to the email, not even a problemnumber or your name. If you must add a comment, put //before the comment so it won’t give errors when sent toScilab.

( )'S PRECEDENCE evaluation order on Thursday's quiz^, then * and /, then + and -.Hence a*b^2-4*d = (a*(b^2))-(4*d)

a*b/c*d = ? add ( )’s to remove ambiguity. (a*b)/(c*d) a*(b/c)*d a+b-c+d = ? rewrite with added ( )’s (a+b)-(c+d) a+(b-c)+d)

MULTIPLE COMMANDS PER LINE

To enter several commands on the same line, separate themwith “;” or “,” Copy/paste to Scilab.

x=1, x=x+1, x=x^2

CLOSED-BOOK QUIZ AT BEGINNING OF CLASS - BE ON TIME No computer, no notes, no text.

1(3) Write a Scilab function. It will be a variant of ahomework problem.

3(2) Write a Scilab formula. The formula for is x

x2 esqrt(x-%pi))/(x^2-%e)

2(2) Be able to calculate the following values:

2*2^3+22*2+3^2(2+3)^2-2^2(-2)^2modulo(13,5) the remainder of 13/5, mod(13,5) in Fortranfloor(13/5) no built-in quotient function but this works.The printf and for commands will not be on the quiz.

WRITE FUNCTIONS IN SCINOTES --The mouse cursor doesn’t work in SciLab but does work in

SciNotes. Do all classwork and homework in SciNotes, neverin the SciLab (you lose 1 point for entering homework in Scilab).

For assigned problems, list the assignment name andfunction description in an initial comment line. Whendefining a function, add at least one testing line after thefunction.

HOMEWORK H1.1(2) vol_box. Write a Scilab functionvol_box(w,l,h) for the volume of a box of height h, widthw, length l. Include a line which uses it to calculate thevolume of 3x3x2 box. Should be 4 more lines, all entered in SciNotes.

//h1.1(2)vol_box vol box(w,l,h) = //volume of box of dimensions w,l,h//Use it to find the volume of a 3x3x2 box.//Ans:18

HOMEWORK H1.2(2) vol_can. Write a Scilab function vol_can(r,h)for the volume of a can of radius rV r2hand height h. Test it on a can of radius 10 and height 4.

Select File/New in SciNotes. File/Save as c2.2(2)vol_can(r,h). // h1.2(2)vol_can vol_can(r,h) =// volume of a can of radius r,height h.// Use it on a can of radius 10, height 4. // Answer: 1256.6371

HOMEWORK H1.3(3) pos_neg. Write a Scilab functionpos_neg(x) (in SciNotes, not SciLab) which returnspositive if x is positive, negative if x is negative andzero if x is 0. Include three lines to test the functions on -2, 0,3. Start with the given code below. Save h1.1(3)pos_neg

//h1.3(3)pos_neg//test on -2,0,3. Ans: negative,zero,positivefunction y=pos_neg(x)

//delete this line, fill in the missing 7 lines. endfunctionclc;disp(pos_neg(3),pos_neg(0),pos_neg(-2))

HOMEWORK H1.4(3) abs_val. Write a your own Scilab functionabs_val(x) (in SciNotes, not SciLab) which calculates theabsolute value of x. Note: if and if |x| x x 0 |x| x x 0Test on values -2,...,2. Note, when asked to write a function,don’t cheat by using its built-in function, abs, in this case. Copy lines, File/New in SciNotes, paste, File/Save as h1.2(3)abs_val.

//h1.4(3)abs_val abs_val(x)=|x|,test on -2..2function y=abs_val(x)

//delete this line, fill in the needed 5 lines. Writing y=abs(x) is cheating.endfunctionclc;printf("\n")for k=-2:2;printf("|%i|=%i\n",k,abs_val(k));end

In the last line, the variables k and abs_val(k)are printed inthe two integer fields %i. Replace %i with %2i. See thedifference?

HOMEWORK 1 DUE BEFORE THE NEXT CLASS - QUIZ ON THIS

H1.1(2)vol_box, H1.2(2)vol_can, H1.3(3)pos_neg, H1.4(3)abs_val email to: [email protected] subject line: 190 h1(10)Copy all to one email body, nothing else; don’t attach files.

HOMEWORK H0(4) DUE NEXT TUESDAY Write these from scratch. On the class website, click Fortran and follow theinstructions to install Fortran and SciTE. http://www.math.hawaii.edu/~dale/190/fortran/fortran-windows-installation.html

Compile and execute (as shown in the above instructions in the

section "Compiling and executing") the following file. Save it asfortran_test.f95

program fortran_test integer i character(6) xx do i = 0 , 6 xx = xx(1:i) // char(i+60) enddo print *, xxend

Send me the 6 characters this program gives when run. email to: [email protected] subject line: 190 h0(4)

Note: Fortran installation can be hard, especially on Macs.On Macs, gfortran is more likely to install than g95. For

Windows 8, try the “SimplyFortran” compilers at the bottomof the “Windows Installation” page. Or maybe try “FTN95”.

HELP, TEXT

To get help enter:help

To get help about matrices, enterhelp matrix

Information needed in exams is in the black declarativesentences. Imperative sentences which give instructions forhomework and classwork are in green. Scilab code is in amonospaced font.

SCILAB ERROR CORRECTION

Scilab/Matlab has no mouse cursor (when a cursor is needed,

use the SciNotes editor window instead). Fix typos, with thebackspace (destructive) or back arrow key (nondestructive). Copy/paste the next line then press <enter> sin[pi*x/12) Retrieve this line using the up arrow.

Use the back arrow key to correct. sin(%pi*x/12) should get 0.8660254

HOMEWORK ERRORS

To make sure your assignment is automatically routed tothe grading program, the subject line must be exactly aslisted for the assignment. It is best to highlight the requiredsubject line and copy/paste it into the email subject line.

Write your homework for SciNotes, not for me. The mostcommon problems are putting lines in the email text such as“Problem 1”. This is not Scilab code and will produce anerror. If you must include such lines, comment them out“//Problem 1”.

If your copied text won’t paste into your email withoutformatting, make sure “plain text” is selected or use “pastewithout formatting” or try <Shift-Control v> to pastewithout formatting. Formatted text can cause errors in Scilab.

To check that your emailed answers will run in Scilab,highlight the entire email message <ctrl-a>, copy <ctrl-c>then paste into Scilab. The problems should run, one after theother, without errors.

Copy/paste text to your emails, don’t attach files. To avoidvirus infections, attached files are not executed.

Copy/pasting text from the Firefox browser to SciNotescan produce errors, try using Chrome instead.

SAVING (optional, not on any quiz or exam)a=[1,2,3; 4,5,6]

When you close Scilab, all values are lost. Here’s how tosave a and all other entered data to some file, say x1.savwith extension .sav.Select file/Save environment from the top left menu.Select Drive H: in the “Save in:” box.Enter prob1.sav in the “File name:” box.a clear //clears all variables, clear a,x clears just a and xa

To load the saved data, select file/Load environment (not file/Open...) and select the filename.

TEXTBOOK Everything on the quizzes and exams will be from the

lectures not the textbook. If you are in the upper half of theclass, the lecture notes should suffice. “C” students will needmore explanations and examples than my one-hour lecturesprovide. In this case you will need to study the Matlab (which

occasionally differs from Scilab) reading assignment given for thatlecture or use one of the Scilab three online texts listed onthe class website. If you don’t understand how programs andfunctions operate, you won’t be able to pass the exams.

QUIZZES Sometimes two people will turn in the same homework

assignment because they worked together on it (that’s fine),sometimes because one copied it from the other (that’s not).Giving a quiz on the homework problem helps to distinguishthe two.

Lecture 2 arithmetic and functionsOpen Lecture 2 on class website: www.math.hawaii.edu/190.Chrome,not Firefox. See Chapter 2 of text for detailed explanation

For each assignment, list the assignment name (and maybe a

function description) in an initial comment line. For everyfunction, add at least one testing line after the function. FORMATTED PRINTING printf

The printf command can print values of variables in asentence or a table with formatting of your own choosing. %i is an integer. %6i is an integer (right-justified) in a field of 6 spaces. %f is a decimal (a floating point number). %.2f is a decimal field with 2 decimal places. %4.2f is a decimal field of 4 spaces, 2 decimal places. Decimal is right-justified in a field of 4 spaces. More than 4 if needed.

%s is a character string. %12s is a string (right-justified) in a field of 12 spaces. \n makes a new line.

EXAMPLE E2.1 format For integers i=1,2,...,12 print 1/i andprint the decimal value. Format decimal to two decimalplaces. The printout should be a follows. -1/1 = -1.00 -1/2 = -0.50 -1/3 = -0.33 -1/4 = -0.25 -1/5 = -0.20

Open SciNotes, Copy/Paste/Save code as e2.1format //e2.1format

clc;printf("\n")for i=1:5 printf(' 1/%i = %4.2f \n',i,-1/i) end

CLASSWORK C2.1(2) format Together. Format with one line perperson. Phone numbers are strings not numbers. Make thecolumns line up (give all character strings the same maximum length).Name: Tom Phone: 1234 Height: 5.60' Name: Dick Phone: 0002 Height: 6.10' Name: Harry Phone: 9999 Height: 5.95'

Copy lines (from Chrome, not Firefox), File/New, paste, File/Save as c2.1(2)format

//c2.1(2)format names, phone numbers, heights name=['Tom','Dick','Harry'] phone=[1234, 0002, 9999] height=[5.2, 5.95, 6.2] clc;printf("\n") for i=1:3 // ' ' prints one '. ' ' is two ' not one double " printf('Name: ___ Phone: ___ Height: ___'' \n', ... name(i), phone(i), height(i) )end

Don’t just have one name name="Tom" but a vector of three name=[name(1),name(2),name(3)]=["Tom","Dick","Harry"] The printf line had to be split over two lines. Write “...” tocontinue a line on to the next line.

RANDOM BEHAVIOR rand()In Scilab (not SciNotes), enter rand() three times. Random

between calls, not between sessions, not between computers.rand() rand()rand()

n=input('Enter a positive integer. > ') allowsthe user to enter a value for the variable n.

CLASSWORK C2.2(2) toss Together. Write a function toss()which tosses a coin giving H or T for heads or tails. Test itby tossing it on a user-entered number of times with tosses inone row. Should get random H’s, T’s.

Copy lines, File/New in SciNotes, paste, File/Save as c2.2(2)toss(). //c2.2(2)coin_toss toss a coin, return H or T //Toss it n times where n is entered by the user.function C = coin_toss()

//delete this line, fill in the missing 6 lines. <shift-tab> moves back 1 indent endfunction clc;printf('\n')n=input("Enter the number of tosses.> ") for i=1:n printf(" %s",coin_toss())

end

VARIABLE LENGTH SUMS AND PRODUCTS

For variable-length sums, start with 0. Add items one at atime to the growing sum. For variable-length products, startwith 1. Append terms one at a time to the growing product. CLASSWORK C2.3(2) series. Together. Write a function f(x,n)which calculates

for any x , n. Test it on f(12,3).x x2

2 x3

3 ... xn

nCopy the two lines, File/New, paste, File/Save as c2.3(2)series //c2.3(2)series Function f(x) = x+x^2/2+... . // Test on f(12,3). Answer: 660.

n! = n*(n-1)*(n-2)*...*2*1. 8!=8*...*2*1=40320CLASSWORK C2.4(2) my_factorial. Together. Write a functionmy_factorial(n) which calculates . Compare with then!builtin factorial(n) on n=8 When writing functions, you maynot use the builtin version.

Copy the 1 line File/New in SciNotes, paste, File/Save as c2.4(2)factorial //c2.4(2)my_factorial test on n=8,ans=40320

CLASSWORK PROBLEMS DUE AT THE END OF EACH CLASS C2.4(1)format, C2.2(2)toss, C2.3(2)series, C2.4(2)my_factorialemail to: [email protected] subject line: 190 c2(8)

Open a browser-based email client. E.g. Gmail, Hotmail, Yahooor click the UH Webmail link on our class website, or go to your MyUH account.

vTo: [email protected] line: Copy/paste subject line 190 c2(8) exactly.vBody: Copy/paste all classwork problems into one message.Copy each problem from SciNotes to the email:

highlight the lines to be copied, press <ctrl-c> or select edit/copy, put the cursor where you wish to paste the lines (two blank

lines below any preceding problem), press <ctrl-v> or select edit/paste.

Add two blank lines after each problem including the last.vTest your email. For each problem, except toss, highlight,

copy <ctrl-c>, paste <ctrl-v> into Scilab. Press <enter>. vSend it.

Don’t attach files (attachments get scrubbed).

Separate problems with one or two of blank lines.Avoid formatting. Paste into email with plain text set or

right-click to get “paste without formatting”. Formatted textcauses errors when run in SciLab. Never send Scilab answers, send only SciNote lines.

Do not add anything else to the email, not even a problemnumber or your name. If you must add a comment, put //before the comment to avoid Scilab errors.

CLOSED-BOOK QUIZ - BE ON TIME No computer, no notes, no text.

A variant of one of your four homework problems.

For each homework problem, copy/paste the comment linesto the top of the file. Put clc after the endfunction line.This gives cleaner output.HOMEWORK H2.1(2) average. Write (in SciNotes, not SciLab) afunction aver(x,y,u,v) which calculates the average ofx,y,u,v. After the function, include a test line which finds theaverage of 1,2,3,4. //h2.1(2)aver aver(x,y,u,v)=(x+y+u+v)/4//add test line disp(aver(1,2,3,4))at bottom//Ans: 2.5

HOMEWORK H2.2(4) series. Write a SciLab function g(x,n)that calculates for any x, n. 1 x x2 x3 ... xn

Add a line which tests on . gx, n x 12, n 3Note: this is . i ranges from 0 to n. x0 x1 x2 ... xn

// h2.2(4)series g(x,n)=1+x+x^2+x^3+ ... // Test g(x,n) on x=12, n=3. Answer: 1885.

HOMEWORK H2.3(4) product Write a SciLab function h(x,n)that on inputs x, n calculates x 1x 2x 3...x nTest it on h(2,4). Fill in the one blank line. //h2.3(4)product h(x,n)=(x+1)(x+2)...(x+n)//Test on h(2,4) Answer: 360.function P=h(x,n)P=1for i=1:n

delete this line, replace with one 1 line ... see the my_factorial function endendfunctiondisp(h(2,4))

HOMEWORK H2.4(2) tossbent Write a function tossbent()which tosses a bent coin which is heads 75% of the time.Test it by tossing this bent coin n times where n is enter bythe user. Rock-paper-scissors instead.

//h2.4(2)tossbent tosses bent coin that is // on average, heads 75% of the time// Print tosses all in one row.

In SciNotes, <tab> moves forward one indent,<shift-tab> moves back one indent. If a title has a *, ithasn’t been saved, <ctrl-s> saves it but so does <F5>.

HOMEWORK 2 DUE BEFORE THE NEXT CLASS Send all in one emailemail to: [email protected] subject line: 190 h2(12)Copy/paste the commented template lines to the top of the file. H2.1(2)average, H2.2(4)series, H2.3(4)product, H2.4(2)tossbent

Reminder: HOMEWORK H0(4) (see previous lecture) is alsodue before the next class. Write hw problems from scratch.

Lecture 3 vectors and matricesOpen Lecture 3 on class website: www.math.hawaii.edu/190 Chrome,not Firefox. See Chapter 2 of text for detailed explanations.

Vectors are sequences of numbers. ROW VECTORS Enter the following in SciLab:

[1,2,3] notation for row vectors[8]= =8 a=[2 3 4] separate entries with spaces or commasb=[10,10,10] commas preferred, required in Fortrana+b, b-a add, subtract the respective coordinates2*a, a+1 scalar product and addition a^2, 2^aa*b wrong dimensions for matrix multiplicationa.*b pointwise multiplication is not matrix muliplicationa(1),a(2),a(3), a(i) = ith entry of vector a

a($)= last, a($-1)= next to last element.

COLUMN VECTORS a=[4;3;2] notation for column vectorsbb' transposeb why didn’t b change? b=b', b b doesn’t change unless a change is assigned.a+b, b-a, a.*b operations are performed component wise.

VECTOR OPERATIONS

sum(a) sum of entries , sum( [4;3;2] ) = 9

prod(a) product of entries, prod( [4;3;2] ) = 24max(a) largest entry max( [4;3;2] ) = 4min(a) smallest entry min( [4;3;2] ) = 2length(a) number of entries in the vector, length( [4;3;2] )=3 (not the geometric length or magnitude of the vector)a(length(a)) = last element = a($), a(1) = first.

DOT (INNER) PRODUCT classwork problem 2.a1, a2, ..., an b1, b2, ..., bn a1b1 a2b2 ... anbn

= the dot product. The dot_product function (built intoMatlab but not Scilab) must work for vectors of any lengthwithout using “...”.

EXAMPLE E3.1 dot_product Write a functiondot_product(a,b) for the dot product of vectors a, b

function P = dot_product(a,b)P = sum(a.*b)

endfunctionclc; disp(dot_product([1,2],[3,4]))//Answer 11disp(dot_product([1,2,3],[4,5,6])) //Answer 32

EXAMPLE E3.2 Write a function H(a) for the sum of thecubes of the components of a vector a, i.e.,

. a13 a2

3 ... an3

Test it on user input. Must work on vectors of any length.

function x=H(a) x=sum(a^3)endfunctionclca=input('Enter a vector. > ') //try [1,2]

disp(H(a)) //on [1,2] ans. is 9

MAGNITUDE (GEOMETRIC LENGTH) a12 a2

2 a32 ... an

2

This formula only for vectors of length 3. The classworkfunction code below must work for vectors of any length.

CLASSWORK C3.1(2) mag Together. Define a function mag(a)which calculates the geometric length of a. Entering the formula

one step-and-test at a time, starting with fixed input. After thefunction, include lines to get the vector a from the user andto display mag(a). If you enter “[1,2,3]” you should get 3.7416574

Copy lines, File/New in SciNotes, paste, File/Save as c3.1(2)mag(a)

//c3.1(2)mag mag(a)=geometric length of a.

//Test on user input: a = input('Enter a vector. > ')

// Entering [1,2,3] should give 3.7416574 //delete this line, write in the three lines for the function

clc;printf('\n')a=input('Enter a vector.>')disp(mag(a))

MATRICES Enter in SciLab: -- repeat all these steps at home.a=[1 2; 3 5] b=[1,1;1,1] [a,b] a followed on the right by b.[a;b] a, with b appended below it.2*b,a+b, a-b, a.*b, a*b [n,m]=size(a) // n= number of rows, m= number columns

a(1,2),a(2,1) a(i,j) = entry in ith row, jth columna(2,2)=4 changes a(2,2) to 4a,a(:,:) a,a(:,1),a(:,2) a(:, j)= all rows of jth column= jth columna,a(1,:),a(2,:) a(i, :)= all columns of ith row = ith rowa, a(1,2)=10 a(:,2)=9 a(1,:)=[7,8] bz=b saves b to z b(1,:)= b(1,:)+2 What does this do? b=z recovers b from z b(:,1)= b(:,1)-2 What does this do? a([2,1],:) result of swapping rows 1, 2 //homework problem

a(:,[2,1]) result of swapping columns 1,2 zeros(2,3)ones(2,3) 8*ones(2,3)

MATRIX MULTIPLICATION, IDENTITY MATRIX, MATRIX INVERSES

a*b matrix multiplication

a11 a12

a21 a22

b11 b12

b21 b22

=a11b11 a12b21 a11b12 a12b22

a21b11 a22b21 a21b21 a22b22

The entry in the ith row and jth column of the product ai j

= dot (or inner) product of the ith row of the first matrix and the jth column of the second matrix.

I=eye(2,2) This is Scilab notation, Matlab uses eye(2).I is the 2x2 identity matrix.

1 is the identity for multiplication of numbers: . 1x x1 xI is the identity for matrix multiplication: Ia aI aa, I*a, a*I,

is the inverse operation of multiplication of numbers:x1

. xx1 x1x 1 is also the inverse operation of multiplication of matrices:x1

a a1 a1 a I

In Matlab/Scilab, the inverse is inv(a). a1

a=[1,2;3,4] inv(a) a*inv(a),inv(a)*a 2.220D-16 2.22 1016 0Computer arithmetic isn’t always exact. 1/3 = .3333333333333333.... .333333

CLASSWORK C3.2(3) id Together. Write a function id(n) whichgenerates the nxn identity matrix. Test on n=4,6. Copy lines, File/New in SciNotes, paste, File/Save as c3.2(3)id

//c3.2(3)id id(n)=nxn identity matrix. //delete this line, fill in the function

clc; disp(id(3)); disp(id(4))

CLASSWORK C3.3(3) add_mult Together. Write a functionadd_mult(a,i,r,j) which adds r times row j to row i.Test add_mult(a,2,8,3) for a=[1,0,0;0,1,0;0,0,1].Copy lines, File/New in SciNotes, paste, File/Save as c3.3(3)add_mult

//c3.3(3)add_mult add_mult(a,i,r,j)

//delete this line, fill in the function

a=[1,0,0;0,1,0;0,0,1]; clcdisp(a); disp(add_mult(a,2,8,3))

CLASSWORK PROBLEMS DUE AT END OF CLASS

C3.1(2)mag, C3.2(3)id, C3.3(3)add_mult

email to: [email protected] subject line: 190 c3(8)To enable automatic routing, copy the subject line exactly.

CLOSED-BOOK QUIZ AT BEGINNING OF CLASS No computer; no text.Like the Hw problems. Be on time. There will be one problem. Itwill be like a homework problem.

HOMEWORK H3.1(3) distance. The distance between points and is a a1, a2, ..., an b b1, b2, ..., bn

a1 b12 a2 b22 ... an bn2

Write a Scilab function for the distance D=distance(a,b)between vectors a and b. Use it to find the distance between[1,2] and [3,3] and the distance between[1,2,3] and[3,3,3]. Your function must work for vectors of any length, it maynot use +...+. See example E3.2 above. Try entering the formula onestep-and-test at a time.

//h3.1(3)distance Use it to find the

//distance between [1,2],[3,3] Answer: 2.23

//distance between [1,2,3],[3,3,3] Answer: 2.23

HOMEWORK H3.2(3) swap Write a Scilab functionswap(a,i,j)which swaps rows i and j. For example,

swap1 2 34 5 67 8 9

, 2, 3 1 2 37 8 94 5 6

Fill in the blank line. See example above.

//h3.2(3)swap swaps rows i, j function b=swap(a,i,j) b=a b([i,j],:)= ______________endfunction //Testing lines a=[1,2,3;4,5,6;7,8,9]; disp(a),disp(swap(a,1,3)) a=[3 3; 6 6]; disp(a),disp(swap(a,1,2))

HOMEWORK H3.3(3) mult Write a Scilab function mult(a,i,r)which multiplies row i by r. For example,

mult1 2 34 5 67 8 9

, 2, 10 1 2 340 50 607 8 9

//h3.3(3)mult mult(a,i,r) multiplies row i by r //test on a=[1,0,0;0,1,0;0,0,1], mult(a,2,8)

HOMEWORK DUE BEFORE NEXT CLASS Write these from scratch. H3.1(3)distance, H3.2(3)swap, H3.3(3)mult email to: [email protected] subject line: 190 h3(9)

ELEMENTARY ROW OPERATIONS

Given a matrix, there are three types of elementary rowoperations: You mayv switch (permute) rows, -- swapvmultiply a row by a nonzero constant, -- multv add a multiple of one row to another row -- add_mult

To pivot on the i-jth entry of a matrix (assumed nonzero)

means using elementary row operations to make that entry 1and all other entries in the jth column 0. The leadingcoefficient of a row is the first nonzero entry. A matrix is inrefuced row echelon form (rref) iff the leading coefficient ofeach row is 1 and it is to the right of the leading coefficientof the previous row.

Lecture 4 matrices and progressionsOpen Lecture 4 on class website: www.math.hawaii.edu/190

ELEMENTARY ROW OPERATIONS swap mult add_multGiven a matrix, there are three types of elementary row

operations: You mayv switch (permute) rows, -- swapvmultiply a row by a nonzero constant, -- multv add a multiple of one row to another row -- add_mult

To pivot on the i-jth entry of a matrix (assumed nonzero)

means using elementary row operations to make that entry 1and all other entries in the jth column 0. The leadingcoefficient of a row is the first nonzero entry. A matrix is inrefuced row echelon form (rref) iff the leading coefficient ofeach row is 1 and it is to the right of the leading coefficientof the previous row.

1 0 1 20 1 2 30 0 0 0

CLASSWORK C4.1(3) pivot Together. Write a functionpivot(a,i,j) which pivots matrix a on row i and columnj. Assume a(i,j)= 0. List a sequence of pivots and swaps(see H3.2(3)) which converts a=[0,2,3,5;2,3,4,6;5,6,6,7] toreduced row echelon form (rref) Copy lines to SciNotes, paste, File/Save as c4.1(3)pivot

//c4.1(3)pivot pivot(a,i,j) pivots on a(i,j)

//delete this line, write the function swap //delete this line, write the function pivot

a=[0,2,3,5;2,3,4,6;5,6,6,7]//convert a to rref.clc;disp(a)

//delete this line, add a sequence of pivots and swaps to get rref

SOLVING SIMULTANEOUS EQUATIONS. Builtin rref(a)EXAMPLE E4.1 Solve Corresponding augmented matrix

2x 4y 2x 3y 3

a 2 4 21 3 3

Solution Reduced row echelon form: x 3

y 2rref a

1 0 30 1 2

Paste these lines directly into Scilab.a=[2,4,2; 1,3,3]rref(a)Execute, get the solution from the rref matrix, hand-write thegeneral answer as a comment.// x=-3, y=2

EXAMPLE E4.2 Solve rref x 2y 3z 44x 5y 6z 75x 6y 7z 8

1 0 1 20 1 2 30 0 0 0

Hence , hence where z is arbitrary. Inx z 2 x 2 zthis case, there are infinitely many solutions, one for each

choice of the arbitrary parameter z. z is arbitrary since thelast row of 0's gives the equation which is always true.0z 0

Paste these lines directly into Scilab. a=[1,2,3,4; 4,5,6,7; 5,6,7,8] rref(a)Execute, get the solution from the rref matrix, hand-write thegeneral answer as a comment. // x=-2+z, y=3-2x, z is arb

CLASSWORK C4.2(2) rref

x 6y 4z 5x 12y 2z 3x 8y z 0

Enter the augmented matrix line and the rref line in SciNotes, not Scilab.

Copy lines, File/New in SciNotes, paste, File/Save as c4.2(2)rref.

// c4.2(2)rref Two SciNote lines, plus comment. Don’t copy answers from SciLab.//delete this, fill in the matrix and rref(a) lines, need disp(a), disp(rref(a)).

// x=1.49,y=______,z= ______ //Write answer in the blanks above, rounded to two decimal places.

ARITHMETIC PROGRESSIONS [n:s:m] .

[0,1,5] row vector[0;1;5] column vector[0:1:5] start with 0, step size 1, end with 5 0:2:8 step size 2, [ ] may be omitted. [1:.1:2] step size .1

0:45 abbreviation for [0:1:4]=[0,1,2,3,4,5][8:1:2][8:-1:2]for i=[3,1,5]; disp(i); endfor i=3:5; disp(i); end

CLASSWORK C4.3(1) progression Write[2.0,1.9,1.8,...,0.0]as a progression: [n:s:m] Copy lines, paste into SciNotes, File/Save as c4.3(1), fill the 3 spaces.

//c4.3(1)progression [1.0,.9,.8,...,0.0]

disp([ : : ])

AREAS AND INTEGRALS Builtin intg(f,a,b) is the integral of function f from a to b, it is thea

b f xsigned area between the function and the x-axis over theinterval . a, b

f(x)

a b

1-1 -1

1

xxx

Area below the x-axis is considered negative.

In Scilab we write intg(a,b,f) for where f mustab f x

be a user-defined function.

EXAMPLE 4.3 Find 1 cos2 x

Paste these lines directly into Scilab.function y=f(x) y=1-(cos(x))^2;

endfunction disp(intg(-%pi,%pi,f)) // should get =3.14...

CLASSWORK C4.4(2) semicircle Together. Calculate the area of theunit semicircle, the top half of . x2 y2 1For a circle of radius is 1, the area is .r2 12 3.14The semicircle area is half of this /2 3.14/2 1.57In , solving for y gives x2 y2 1

y 1 x2

is the upper semicircle. f x 1 x2

Define the upper semicircle function . f xUse the integral intg(a,b,f) to get upper semicircle area. Copy lines, File/New in SciNotes, paste, File/Save as c4.4(2)semicircle.

//c4.4(2)semicircle Define upper semicircle function.

//Use intg to find the circle area. Ans: 3.14 b

To approximate the integral, divide the line segment a, binto equal-width segments. Above each segment draw arectangle whose height is the function’s value. The sum ofthe (signed) areas of these rectangles is a Riemann sum. Thesmaller the rectangle width, the more accurate theapproximation.

f(x)

a bCLASSWORK C4.5(4) my_intg Together. Write a functionmy_intg(a,b) which uses Riemann sums with rectanglesof width, to calculate the integral of a1/105 a

b f xdxuser-defined function f . Define the function f x 1 x2

Find the integral using your function my_intg(a,b) Copy lines, File/New in SciNotes, paste, File/Save as c4.5(4)my_intg.

//c4.5(4)my_intg Riemann sums. Ans: 1.57function y=f(x) y=sqrt(1-x^2) endfunction function rsum=my_intg(a,b)

//delete this, write the function my_intg here

endfunction clc;printf("\n")printf("My area = %f \n", my_intg(-1,1))printf("Scilab''s = %f \n",intg(-1,1,f))

CLASSWORK C4.6(3) pos_prod Together. Write a functionpos_prod(a) which finds the product of the positive entriesin the matrix a. Test with the given lines.Copy lines, File/New in SciNotes, paste, File/Save as c4.6(3)pos_prod.//c4.6(3)pos_prod pos_prod(a)=product positive

entries

//delete this, write the function pos_prod(a)

a = [1,0,-2; 3,0,-4; -5,6,0]; //ans=18disp(a),printf(" pos_prod = %i \n",pos_prod(a)) a = [1,-2; 3,-4]; //ans=3

disp(a),printf(" pos_prod = %i \n",pos_prod(a))

CLASSWORK DUE AT END OF CLASS

C4.1(3)pivot, C4.2(2)rref, C4.3(1)progression , C4.4(2)semicircle,C4.5(4)my_intg, C4.6(3)pos_countemail to: [email protected] subject line: 190 c4(15)

HOMEWORK H4.1(2) pivot Use the classwork functionpivot(a,i,j)to convert a=[3,0,3,5;2,0,4,6;5,6,6,7] toreduced row echelon form. In CLASSWORK C4.1(3) the first stepwas to swap the first two rows to ensure that desired first enty was nonzero. .This isn’t a problem here and the first step is not a swap. But a swap is neededlater on.

//h4.1(2)pivot add lines to convert//a=[3,0,3,5; 2,0,4,6; 5,6,6,7]

HOMEWORK H4.2(2) rref x 16y 4z 50x 12y 2z 302x 4y 6z 80

Enter the augmented matrix line and the rref line in SciNotes, not Scilab.

// h4.2(2)rref SciNote lines, plus comment. Don’t copy answers from SciLab. If the bottom rref row is all 0, z is an arbitrary variable as in EXAMPLE E4.2

//delete this, fill in the matrix and rref(a) lines

// x=______,y=______, z=______ //Write answer in the blanks above, rounded to two decimal places.

HOMEWORK H4.3(2) my_intg Define the function f x sinxFind the integral from 0 to using your functionmy_intg(a,b). You need to have function code for f and function

code for my_intg. No credit for using the built-in intg.

//h4.3(2)my_intg integral sin(x) from 0 to pi

//Ans: 2

HOMEWORK H4.4(3) countup In SciNotes, write a functioncountup(n)which generates the nxn matrix whose entries,when read in the row-column order are 1,2,3,...,n*n. For n=2, countup(2)=[1,2; 3,4]. For n=3, countup(3)=[1,2,3;4,5,6;7,8,9]Fill in each of the two blanks with a single letter/digit.

//h4.4(3)countup function b=countup(n)C=1for i=1:n, for j=1:nb(i,j)= _____ //hint: single letterC = C+ _____ // hint: single digit

end; endendfunctionfor i=2:4 disp (countup(i))

end

HOMEWORK H4.5(3) pos_sum Write a function pos_sum(a)which totals the positive entries in the matrix a. Test with these lines. Like classwork pos_prod(a) but a growing

sum instead of a growing product.

//h4.5(3)pos_sum pos_sum(a)=sum of positive entries//delete this. write the function pos_sum (a) here,

a = [1,0,-2;3,0,-4; -5,6,0]; //ans=10disp(a),printf(" pos_sum = %i \n",pos_sum(a)) a = [1,-2;3,-4]; //ans=4

disp(a),printf(" pos_sum = %i \n",pos_sum(a))

HOMEWORK H4.6(3) pos_count Write a functionpos_count(a) which counts the number of positive entriesin the matrix a. Test with the given lines.Copy lines, File/New in SciNotes, paste, File/Save as h4.6(3)pos_count.//h4.6(3)pos_count pos_count(a)=# positive entries

//delete this write the function pos_count(a) herea = [1,0,-2;3,0,-4; -5,6,0]; //ans=3disp(a),printf(" pos_count = %i \n",pos_count(a)) a = [1,-2;3,-4]; //ans=2disp(a),printf(" pos_count = %i \n",pos_count(a))

HOMEWORK DUE BEFORE NEXT CLASS - QUIZ ON ONE OF THESE

H4.1(2)pivot , H4.2(2)rref, H4.3(2)my_intg, H4.4(3)countup, H4.5(3)pos_sum,H4.6(3)pos_countemail to: [email protected] subject line: 190 h4(15)

190 Lecture 5 graphs Open Lecture 5. Open Scilab/SciNotes.

EXTRA CREDIT Extra credit for being the first to find an errorin the online lectures, quizzes or exams.

INSERT MODE / OVERTYPE MODE In SciNotes, type something, asdfasdf. Move your cursor

to the beginning. Press the <insert> key. Type some more,press <insert> again, type some more. If you cursorsuddenly becomes fat, you accidently hit <insert>.

ONE-VARIABLE FUNCTION GRAPHS

PLOTTING POINTS We want to plot four points: (0,1), (1,2), (2,4), (3,3).

CLASSWORK C5.1(1) plot Together.Copy lines, paste to SciNotes, File/Save as c5.1(1)plot.In the function (graphics) window, click edit / figure properties.

// c5.1(1)plot Plot the following points.// (0,1), (1,2), (2,4), (3,3). x =[ ] // Fill in vector of x coordinatesy =[ ] // Fill in vector of y coordinatesclc;clf //clf Clears the graph window. It is required.plot(x,y) //Scilab chooses the line styleplot(x,y+1,'g') //change g to r to make a red line.

GRAPHING FUNCTIONS

Recall: are written, asin, acos, atan. sin1, cos1, tan1

An interval involves infinitely many points. As a,stand in for these infinitely many points we use a vector of alarge number of points between the endpoints, in this case-%pi:0.01:%pi.

EXAMPLE 5.1 plot Graph sin(x)Copy lines, File/New in SciNotes, paste, File/Save as e5.1plot. // e5.1plot y=sin(x) over [-pi,pi]x=-%pi:0.01:%pi; y=sin(x); //need ; to suppress printing in Scilab

plot(x,y) //need required clc;clf before plot

The above four lines can be rewritten in one line (use this in the

last classwork):

clc;clf;plot(-%pi:0.01:%pi,sin)

Likewise, plot(x,f)graphs a user-defined function f.

function y=f(x) y= 1-cos(x^2) endfunction clc;clf;plot(-%pi:0.01:%pi,f)

TANGENT LINES

For a function f and a point a on the x-axis, is thea, f apoint on the graph above a. The tangent line at this point isthe straight line through this point which best fits the graph.The slope m of the tangent is called derivative of f an x. It iswritten .m f a

The slope of the brown “secant” line is . m f a h f a

hAs h goes to zero, the secant line approaches the tangent lineand the slope of the secant line approaches the slope off a

the tangent. Hence . Hence f a limh0f a h f a

h is approximately the tangent slope whenm

f a h f ah

h is very small, say = one millionth. h 1/106

f(a+h)-f(a)

f(a)f(a+h)

h

a a+h

(a+h, f(a+h))

(a, f(a))

a

(a, f(a))

f

slope = f '(a)

Since the tangent has slope m and goes through the point , the equation for the tangent is a, f a

hencey f a mx ay mx a f a

CLASSWORK C5.2(3) tangent Together. Plot over f x 1 x2

. Write a function tangent(a)which given an2, 2interval vector x and function f finds the y values of thetangent line to f at (a, f(a). Use it to plot a red line tangent tof at and plot a green line tangent at 1, f 1 1/3, f 1/3Copy lines, File/New, paste, File/Save as c5.2(3)tangent

// c5.2(3)tangentfunction y=f(x) y = sqrt(1-x^2)endfunctionx = -1:.01:1;

function y=tangent(a)//delete this line, fill in function

endfunctionclc;clf;plot(x,f)plot(x,tangent(-1/2),'r')plot(x,tangent(1/3),'g')

CONTOUR PLOTS Not on a quiz or closed book exam.

Draw a contour graph and a 3D graph of z 1 x2 y2

= an upper hemisphere. For Classwork 1 and 2, you willgraph . z xy

CLASSWORK C5.3(2) contour Together. Write 7 lines in SciNoteswhich generate a nice contour plot of . Set the numberz xyof contour levels to 15. Copy lines, File/New, paste, File/Save as c5.3(2)contour. Execute. Then change the red characters to graph xy . Should get a saddle.

// c5.3(2)contour Change to make a contour plot of z=xy. x= -2:.01:2; //;suppresses printing in Scilab y= -2:.01:2; // ;is required to run in the Scilab window.for i=1:length(x); for j=1:length(y); z(i,j)= sqrt(1-x(i)^2-y(j)^2); //need ;end; end clc;clf //Clear the graph window.contour(x,y,z,5) //5 = number of levels. Play with it.

The example gives the map of a dome;z 1 x2 y2

your problem gives the map of a saddle. bz xy

3D GRAPHS Not on a quiz or closed book exam.

CLASSWORK C5.4(2) 3Dgraph Together. Write 4 SciNote lineswhich generate a 3D graph of z=xy. Copy lines, File/New, paste, File/Save as 5.4(2)3Dgraph. Execute. Then changethe red characters to graph xy. Should get a saddle. In graph window click tools / 3D

rotation, drag cursor in window.

// c5.4(2)3Dgraph Change to make a 3D graph of z=xy.[x,y]=meshgrid(-1:.1:1); //;suppresses Scilab printing z=sqrt(1-x.^2-y.^2); //x, y are matrices, the "." is requiredclc;clf //Clear the graph window. mesh(x,y,z)

Should get a saddle. If you get a flat surface, you wrotez=x*y, instead of z=x.*y. If you get a partially flat surfaceor if two quadrants are blank, you probably wrote z=sqrt(x.*y). If you get a dome, you didn’t change theformula from to . 1 x2 y2 x y

CLASSWORK C5.5(1) plot On your own. Plot arctan over [-10,10]Copy the single pink line of EXAMPLE 5.1, File/New, paste, File/Save asc5.5(1)plot. Modify the line to graph arctan (atan) over [-10,10].

// c5.5(1)plot arctan over [-10,10].

CLASSWORK DUE AT END OF CLASS

C5.1(1)plot, C5.2(3)tangent C5.3(2)contour, C5.4(2)3Dgraph, C5.5(1)plotemail to: [email protected] subject line: 190 c5(9)Test each email problem in Scilab before sending.

HOMEWORK H5.1(1) plot_bell Define the function .f x ex2

Plot this “bell-curve” function over the interval . Note,3, 3write a function as in the paragraph above, not just a formula as in theclasswork above.

// h5.1(1)plot the function f(x)= %e^(-x^2) over [-3, 3] clffunction y=f(x)

//delete this line, finish the problem, don't forget the required ;

HOMEWORK H5.2(3) tangent Plot the natural log function over . Use the function tangent(a)f x lnx 1/10, 2

above to plot a red line tangent to this graph at 1/2, f 1/2and plot a green line tangent at . 1, f 1// h5.2(3)tangent

HOMEWORK H5.3(2) contour Write 6 lines in SciNotes whichgenerate a nice contour plot of . Not on a quizz x2 xy y2

or closed book exam.

// h5.3(2)contour Code for contour plot of z=x^2-xy+y^2 // Should be round contours. // see math.hawaii.edu/~dale/190/contour.png clc;clf

HOMEWORK H5.4(2) 3Dgraph Write 4 lines in SciNotes whichgenerate a nice 3D graph of . Not on a quiz orz x2 xy y2

closed book exam. In graph window click tools / 3D rotation, drag cursor in window.

// h5.4(2)3Dgraph Code for 3D graph of z=x^2-xy+y^2// Should be a bowl shaped valley. These are pointwise matrix products and powers. // If you don't get a bowl, you missed one of the needed three dots "." .

// see http://math.hawaii.edu/~dale/190/3Dsaddle.png

HOMEWORK DUE BEFORE NEXT CLASS email to: [email protected] subject line: 190 h5(8)H5.1(1)plot_bel, H5.2(3)tangent , H5.3(2)contour, H5.4(2)3DgraphSubmit only the SciNote code, don’t attach graphs.Include clf to clear the function window and clc to clear the console window.

COMMON ERRORSThe most common error for homework H5.4(2) is forgetting to

insert the three “.” needed for pointwise multiplication.If you computer doesn’t seem to be doing anything, select

Control/Abort in Scilab to stop any unterminated previousprogram.

Do classwork/homework in SciNotes, not Scilab. But, beforesending your email, copy each problem to Scilab and check thateach runs without errors. Don’t attach graphs.

If you can’t complete the classwork on time, study the classworkahead of time. Don’t “reinvent the wheel”. For each homeproblem, there is a corresponding problem in the lecture notes.Copy/paste this corresponding problem into SciNotes. Modify thecode to fit your problem. But, after getting the program to run,open a new window and see if you write the program from scratch.This doesn’t apply to the contour or 3Dgraph problems as theywon't be on any quiz or test.

190 Lecture 6 Bar charts, histogramsOpen Lecture 6. Open Scilab/SciNotes.

BAR CHARTS

We often graph statistical data with a bar chart orhistogram. Suppose we ask 10 students how many years theyhave been at UH. The list of answers might be

y =[1,2,1,1,4,0,0,3,3,2] // the unsorted list of answers

mtlb_sort(y) = [0,0,1,1,1,2,2,3,3,4] // sorted list

y = mtlb_sort(y) // sorts the list yGiven an input list y, mtlb_sort outputs a sorted copy of y. Asalways with functions, it doesn't change the input y. To actuallychange y to a sorted list, write y = mtlb_sort(y).values = [0,1,2,3,4] // the list of values (no repetition)

freqs = [2,3,2,2,1] // the frequencies of the values. (0 occurs 2 times and 1 occurs 3 times, ..., and 4 occurs 1 time).

The built-in function mtlb_sort gives the sorted list. Fromthe sorted list, list the vector values of values and thevector freqs of their frequencies. The built-in function barmakes a bar graph from the list of values and the list offrequences.

CLASSWORK C6.1(1) bar Make a bar graph. Write code inSciNotes which sorts the values, clears any previous graphand makes a bar graph of

w= [3,5,7,5,2,3,3,5,5,4,4,4,9,7,7,2,2] .

The example below is for a dataset y of values. You need to change thered characters to solve your problem for the dataset w of values. Copy lines, File/New in SciNotes, paste, File/Save as c6.1(1)bar

//c6.1(1)bar //List the values, list the frequences, draw a bar graph. //This example y has 5 bars, your w has 6 bars with two gaps.// w= [3,5,7,5,2,3,3,5,5,4,4,4,9,7,7,2,2]

//Change the red line.clc;clfy=[1,2,1,1,4,0,0,3,3,2]; //This y is not your w.

disp("The given list:"); disp(y)disp('The sorted list:') disp(mtlb_sort(y)) // mtlb_sort(y) sorts the values of y //values =[ ] //enter the values without repetitions//freqs = [ ] //enter their frequencies, uncomment these lines //bar(values,freqs) // don’t write bar(y).

If you get 5 bars, you didn’t replace y with w.

NORMAL DISTRIBUTION Here is a normal distribution(bell-curve) with mean (average) m and standard deviation s.

m m+sm-s

Normal Curve

34%

Data values >>

Pro

babi

li ty

>>

About a third of the distribution is 1 std. dev. above the mean m, athird is 1 std. dev. below m; a third is more than 1 std. dev. from m.

HISTOGRAMS Suppose the weights of UH students have a normal

distribution with mean (average) 130 and std. dev. 10. For large sets of data such as this, with too many bars,

group the data into groups such as 60-70 70-80, 90-100, ... .the height of bar will be the frequency (number of elements) ofthe group. This is a histogram.

Fre

quen

c ey

>>

60 70 80 90 100 110 120 130Data values >>

CLASSWORK C6.2(2) histogram Together.

Copy lines, File/New, paste, File/Save as c6.2(2)histogram

//c6.2(2)histogram group size = 2.

v=grand(1,100,'nor',130,20); //replace this line with next// v = [3,5,7,5,2,3,3,5,5,4,4,4,9,7,7,2,2];// grand generates a random list with //1 row, 100 columns, 'nor' means 'normal distribution' ,// 130 is the mean, 20 is the standard deviation. clc;clf;histplot(60:10:200,v) //change this line // 60 is where the histogram starts, 10 is the group size, 200 is the end.// hit <F5> several times, note that the histogram changes

Widely spread out data has a large std. dev.; closelygrouped data has a small std. dev. Note the difference below.

Change the std. dev. from 20 to 10 then <F5>. Change the std. dev. from 20 to 40 then <F5>.

The code above generated random data using grand. Deletethat line and instead make a histogram for the data v =

[3,5,7,5,2,3,3,5,5,4,4,4,9,7,7,2,2]

Set start to 1 less than the lowest value. Set group size to 2. Set end to 1 more than the highest value. Your graph should have 4 bars. Use the given data v, not random data v=grand(1,100... generates.

MEAN, MEDIAN, STD. DEV.mean(w) //mean or average valuestdev(w) //standard deviation of a samplemedian(w) //medianThe median of a list (vector) of values is the middle value ofthe sorted list if the list has an odd number of values and thethe average of the two middle values if the list has an evennumber of values. If the list is [2,3,1], then the sorted listis [1,2,3] and the median is the middle value 2. If the listis [3,2,1,3], then the sorted list is [1,2,3,3] and the

median is .23

2 52

If , the mean or average is .a a1, a2, ..., ana1a2...an

nThis is computed by the built-in function mean(a).

RECALL FLOOR, CEILING Let x be a real number and n, d be integers.floor(x) is the nearest integer below x, ceil(x) is the nearest integer above x, floor(.7)=0, ceil(.3)=1If a is a list of values (a vector), and n=length(a), then1 is the first position, n=length(a) is the last, the average of 1, n mid=(1+n)/2 is the middle position (it is an integer iff n is odd),a(1) is the first item, a(n) is the last item. a(mid) is the item in the middle position if n is odd.

For a= [x,y,z], 1= first position, 3= last, mid=(1+3)/2 = 2 = the middle position. a(1) = x = item, a(3) =z = last item, a(mid)=a(2) = y = middle item.

For a=[x,y,z,w], y, z are the two middle items. The averageposition is (1+4)/2=5/2=2.5. The two integer middle positions arefloor(2.5)=2 and ceil(2.5)=3. Hence, if n=length(a) is even, mid1=floor((1+n)/2), mid2=ceil((1+n)/2) are the middle positions. a(mid1), a(mid2) are the items in these positions.

After the list has been sorted (use a=mtlb_sort(a)), the median iseither the item a(mid) in the middle position (for lists of odd length)or (for lists of even length) the average of the two middle items[a(mid1)+a(mid2)]/2.

CLASSWORK C6.3(2) odd_median Write odd_median(a) whichcomputes the median of a list (i.e., vector) a of odd length. Copy lines, File/New, paste, File/Save as c6.3(2)odd_median

//c6.3(2)odd_median median of items in a.function median=odd_median(a) //delete these lines, n=length(a), sort using mtlb_sort(a)

//middle position= mid=(1+n)/2 //median = value at mid = a(mid)

endfunction clc;printf("\n")a=[30,10,20];disp(a);disp(mtlb_sort(a))printf("median=%i\n",odd_median(a)) //ans 20 a=[40 50 20 10 40];disp(mtlb_sort(a))printf("median=%i\n",odd_median(a)) //ans 40

CLASSWORK C6.4(2) my_mean On your own. Write your ownfunction my_mean(a) which returns the average of thevalues of a vector a. Recall sum(a) adds the elements ofvector a; length(a) is the number of elements. May not usethe built-in function mean.

Copy lines, File/New in SciNotes, paste, File/Save as c6.4(2)my_mean

//c6.4(2)my_mean Find a vector's average. function m = my_mean(a) //delete this line, fill in the 1 or 2 function linesendfunctiona=[3,2,4],printf(" mean=%.2f\n",my_mean(a)) //ans 3a=[5,3,1,1,5],printf(" mean=%.2f\n",my_mean(a)) // ans 3

CLASSWORK DUE AT END OF CLASS

email to: [email protected] subject line: 190 c6(7)Test each email problem in Scilab before sending.C6.1(1)bar, C6.2(2)histogram, C6.3(2)odd_median, C6.4(2)my_mean

NEXT QUIZ One of these homework problems.HOMEWORK H6.1 (3) reverse_sort Write a functionreverse_sort(a) which sorts a vector in descending

order. Negate a, apply mtlb_sort, then negate again. Addlines which test the function on vectors [3,1,2] and [4,3,1,3] . Recall that -a and mtlb_sort(a) do not change a but a=-aand a=mtlb_sort(a) do change a.//h6.1(3)reverse_sort.

Let m be the mean. The standard deviation of an n-elementsample (a randomly selected subset of the entire population) is

The standard deviation of thea1m2a2m2...anm2

n1

entire population is a1m2a2m2...anm2

n

HOMEWORK H6.2(3) stdev_pop Write your own Scilab functionstd_dev_pop(a) which computes the population standarddeviation of the values of a vector a. The formula is

where m is the mean value. Usea1m2a2m2...anm2

n

built-in functions mean and length to calculate m and n. Use it to find the std. dev. of [1,2,3] and [1,2,3,3].//h6.2(3)stdev.pop = population stand. dev. // Add testing lines which apply it to [1,2,3] and [1,2,3,3] // Answers: .816... and .829...

HOMEWORK H6.3(3) even_median Write even_median(a)which computes the median of a list (i.e., vector) a of evenlength. Like odd_median but uses (a(mid1)+a(mid2))/2//h6.3(3)even_median = median of items in vector a.function med=even_median(a) .//delete these line, reuse lines for odd_median, use floor, ceilendfunctionclc;printf("\n")a=[40,20,50,10];disp(mtlb_sort(a))

printf("median=%i\n",even_median(a)) //ans 30 a=[40 50 20 10 0 60];disp(mtlb_sort(a))printf("median=%i\n",even_median(a)) //ans 30

The transpose of a matrix is its reflection across the maindiagonal. The first row transposes to the first column, thesecond row to the second column, ... . An entry ai, jbecomes in the transpose. aj, iHOMEWORK H6.4(4) my_transpose Write a functionmy_transpose(a) which returns the transpose of a. Nocredit for using the built-in transpose function a'. Applyyour function to the matrices a and b below. a=[1,2; 3,4; 5,6] and b=[1,2,3; 4,5,6]then a'=[1,3,5; 2,4,6]and b'=[1,4; 2,5; 3,6].//h6.4(4)my_transpose Do not use the built-in 'function b=my_transpose(a)[n,m]=size(a)for i=1:n; for j=1:m b(j,i)= ___________ // fill the blankend; end;endfunctiona=[1,2; 3,4; 5,6]; disp(a); disp(my_transpose(a))

b=[1,2,3; 4,5,6]; disp(b); disp(my_transpose(b))

HOMEWORK DUE BEFORE NEXT CLASS. email to: [email protected] subject line: 190 h6(13)H6.1(3)reverse_sort , H6.2(3)stdev_pop, H6.3(3)even_median,H6.4(4)my_transpose

190 Lecture 7 Formatted matrix printingOpen Lecture 7. Open Scilab/SciNotes.

Recall, the function values(a) lists the values of vector ain increasing order without repetition. Hence ifa=[1,1,2,3,0,0,1], then values(a)=[0,1,2,3]. The repeatedelements (the red ones) are omitted. The function freqs(a)counts the number of times (the frequency) each value occurs.freqs(a)=[2,3,1,1] since 0 occurs 2 times, 1 occurs threetimes, ... . If a=[5,1,1,0,1,5] then values(a)=[0,1,5] andfreqs(a)=[1,3,2]. CLASSWORK C7.1(3) freqs Together. Write a function freqs(v)which lists, in order, the frequencies of the values (listed in

increasing order) of the vector v.Copy lines, File/New in SciNotes, paste, File/Save as ...

//c7.1(3)freqsfunction f = freqs(v)

//delete this line, write the freqs function

endfunctiona=[5,1,1,0,1,5];disp(a);disp(mtlb_sort(a));disp(freqs(a))//Ans:[1,3,2]a=[4,4,4];disp(a);disp(freqs(a)) //Ans:[3]

Copying vs. assigning. For variables (i.e., memory locations),the assignment y=x sets y equal to x. This is the same ascopying x to y.

EXAMPLE 7.1 replace Let v be a vector of integers. Thefollowing function replace(v,k,x) replaces the number inposition k with the number x. The previous occupant is lost. //e7.1replacefunction w = replace(v,k,x)v(k)=x

endfunction v=[3,4,5,6];disp(v)w=replace(v,2,14);disp(w)

replace(v,2,9) replaces what is at position 2 with 9.

w(1)= 0w(2)= 9w(3)= 2w(4)= 3w(5)= 4

v(1)= 0v(2)= 1v(3)= 2v(4)= 3 v(5)= 4

CLASSWORK 7.2(3) insert Let v be a vector of integers. Writea function insert(v,k,x) which, for a given index k in1:n copies records from positions k:n down to positionsk+1:n+1 and then copies the number x to position k. insert(v,2,9) inserts 9 at position 2 in

v on the left, giving w on the right

w(1)= 0w(2)= 9w(3)= 1 w(4)= 2w(5)= 3w(6)= 4

v(1)= 0v(2)= 1v(3)= 2v(4)= 3 v(5)= 4

Copy lines, File/New in SciNotes, paste, File/Save as ...

//c7.2(3)insert function w=insert(v,k,x)

//delete this line, write the insert function

endfunctiona=1:3for k=1:4; printf("\nInsert 10 at position %i",k)

disp(a);disp(insert(a,k,10)); end

CLASSWORK 7.3(3) find_first Let v be a list of n integers and letx be an integer which may or may not be in the list. Write afunction find_first(v,x)which finds the first position(index k) of x in the list. If x is not in the list, return 0. Thislast value, the value you return if the find loop fails, is calledthe default value. It must be assigned before the loop.find([7,7,5,5],1)=0 find([7,7,5,5],7)=1 find([7,7,5,5],5)=3

Copy lines, File/New in SciNotes, paste, File/Save as ...

//c7.3(3)find function k=find_first(v,x)

//delete this line, write the find_first function

endfunctionclc;v=[5 5 6 6 7 7];disp(v)for x=4:8 printf("Item sought=%i",x) printf(" First position found=%i \n",find_first(v,x))end

CLASSWORK C7.4(3) matrix_printer Together. Write a functionmatrix_printer(a)which prints a matrix with

right-justified columns and 2 decimal-place reals in 6-placefields. The result should look like 1.00 1.00 0.50 0.00 1.00 1.00 0.50 0.00 1.00 0.00 0.50 10.00 1.00 0.00 0.50 10.00 Copy lines, File/New in SciNotes, paste, File/Save as ...

//c7.4(3)matrix_printer

function matrix_printer(a) //no returned value//delete this line, write the matrix_printer function

endfunctionclc; a=[1.00 1.00 1.00 1.00 1.00 0.00 0.00 0.00 1.00 1.00 0.00 10.00 1.00 0.00 0.50 10.50 ] matrix_printer(a)

CLASSWORK C7.5(3) row_sum Together, one step and test at atime. Write a function row_sum(a) which given a matrix aof reals, returns a matrix b which starts with matrix a andthen adds a new column on the right. Each item of the newcolumn is the total of the row preceding it. If a=[ 1.00 0.00 0.50 0.001.00 1.00 0.50 0.00 1.00 1.00 0.50 10.00 1.00 0.00 0.50 10.00 ] then row_sum(a)=[1.00 1.00 0.50 0.00 2.50 1.00 1.00 0.50 0.00 2.50

1.00 0.00 0.50 10.00 11.50 1.00 0.00 0.50 10.00 11.50 ] Copy lines, File/New, paste, File/Save as ...

//c7.5(3)row_sum

function b=row_sum(a)//delete this line, write the function row_sum

endfunctiona=[1.00 0.00 0.50 0.00 1.00 1.00 0.50 0.00 1.00 1.00 0.50 10.00 1.00 0.00 0.50 10.00 ];disp(a)

b = row_sum(a); matrix_printer(b)

CLASSWORK DUE AT THE END OF CLASS

email to: [email protected] subject line: 190 c7(15)C7.1(3)freqs, C7.2(3)insert, C7.3(3)find_first, C7.4(3)matrix_printer,C7.5(3)row_sum

HOMEWORK H7.1(3) values Write the function values(a)which lists the values of vector a in increasing order withoutrepetitions. If a=[1,1,2,5,0,0,1], then values(a)=[0,1,2,5].

//h7.1(3)values //delete this line, write the values function

clc;a=[5,1,1,0,1,5]; disp(a); disp(mtlb_sort(a))disp(values(a)) //ans:[0,1,5]a=[4,4,4]; disp(a); disp(values(a)') //ans:[4]

Printing a vector in reverse order is easy. This line does it:for i=length(a):-1:1; disp(a(i)); end

Writing a function which returns a vector which lists inb athe reverse order is harder.

Index method: If then a a1, a2, ..., an1, an b . Let i range overb1, b2, ..., bn1, bn an, an1, ..., a2, a1

the indices of b and j range over the indices of a. Then provided we calculate j correctly. When i=1, j=n.bi aj

When i increases to 2, j decreases to n-1. Hence we shouldstart with j= n, then, for each iteration of the for i=1:n loop, set b(i) = a(j) and then update j for the next iteration,j = j-1.

Append method: Start with b=[ ], then for i=n:-1:1,append a(i) to b, b=[b,a(i)].

Clever method: consider this example: a([3:-1:1]). Warning, this is not the reverse_sort of lecture 6, no sorting is done here,just listing the elements of a in the opposite order they occur in a. If youare clever, instead of the above, HOMEWORK H7.2(3) reverse Write a function reverse(a)which returns the result of listing the elements of a in thereverse order. If a =[1,3,2,4] thenreverse(a)=[4,2,3,1]. This function returns a vector, itdoesn't print anything.

//h7.2(3)reverse list a in opposite order //delete this line, write the reverse function

clc;a=[4,2,3];disp(a);disp(reverse(a)) //Ans:[3,2,4]a=[9,0,1,2,2];disp(a);disp(reverse(a))//Ans:[2,2,1,0,9

]

HOMEWORK 7.3(3) delete Let v be a list of n integers. Write afunction delete(v,k) which, given k in 1:n deletes thekth element of v and moves any elements below the kthposition up to close any gap. Those at positions k+1:n moveup to positions k:n-1 giving a vector of length n-1.

Deleting the element in position k=2 element from the listv on the left, gives the shorter w on the right.

w(1)= 0w(2)= 2w(3)= 3w(4)= 4

v(1)= 0v(2)= 1v(3)= 2v(4)= 3v(5)= 4

//h7.3(3)deletefunction w=delete(v,k) n=length(v) w(1:k-1)= ___________ // fill the blank w(k:n-1)= ___________ // fill the blankendfunctionclc;v=1:5;for k=1:5 ; printf("\nDelete at position %i ",k) disp(v);disp(delete(v,k))end

HOMEWORK H7.4(3) column_average Write a functioncolumn_average(a) which given a matrix a of reals,returns (returns, not prints) a matrix b which starts with matrix aand then adds a new row at the bottom. Each item of the new

row is the average (mean) of the column above it. Use thebuiltin function mean(a) to get the average. If a=[1.00 0.00 0.50 0.00 0.00 1.00 1.00 0.50 0.00 0.00 1.00 1.00 0.50 10.00 0.00 1.00 0.00 0.50 10.00 0.00]

then column_average(a)= 1.00 1.00 0.50 0.00 0.00 1.00 1.00 0.50 0.00 0.00 1.00 0.00 0.50 10.00 0.00 1.00 0.00 0.50 10.00 0.001.00 0.50 0.50 5.00 0.00

A program which just prints the lines above will only get you1 point. The function column_average must return a vectorand must not have any print statements. All printing is doneusing matrix_printer whose code must be included inthe file.

//h7.4(3)column_average//replace this line with the matrix_printer function

function b=column_average(a)[n,m]=size(a); b=a//delete this line, finish the 3 remaining lines

endfunctionclc; a=[1.00 0.00 0.50 0.00 0.00 1.00 1.00 0.50 0.00 0.00 1.00 1.00 0.50 10.00 0.00

1.00 0.00 0.50 10.00 0.00]

b =column_average(a);matrix_printer(b)

HOMEWORK DUE BEFORE NEXT CLASS. email to: [email protected] subject line: 190 h7(12)H7.1(3)values, H7.2(3)reverse, H7.3(3)delete, H7.4(3)column_average

190 Lecture 8 logic Midterm 2 weeks from todayOpen Lecture 8. Open Scilab. See text Chapter 4. Put a blank line after the last homework/classwork problem - automated grader may hang on last line if no blank follows. FOR-LOOPS

Use for-loops to calculate counts, sums, products, lists,logical or’s, logical and’s. The loop takes care of increasing acount, adding to a sum, or finding a logically true or falsecase. Start with what the answer will be if the for-loop findsnothing. At each stage, the variable holding thecount/sum/product/list is the correct value as seen so far.

Counts and sums start with 0, which is the answer if theloop finds nothing. Products start with 1. A list of items startswith the empty list [ ] which is the answer if nothing isfound. When something i is found, add it to the list: a=[a,i].If the loop takes care of setting a truth value v true, %t, startwith false, v=%f which is the correct answer until the loopsets it to true. If the loop takes care of setting the answer totrue, %t, start with %f which is the correct answer until theloop sets it to true. Start a search for a minimum elementwith , start a search for a maximum with .

LOOP EXITS:break gets you out of the current loop. return gets you out of the function.continue starts a new iteration of the loop from the top.while(??) loops until ?? is true.

CLASSWORK C8.1(3) rev_rows Together. Write a functionrev_rows(a) whose value b reverses the rows of matrix a.You are to make a vector with the reversed rows, not printrows in reverse order. The function has no printf, no disp.Copy lines, File/New in SciNotes, paste, File/Save as ...

//c8.1(3)rev_rows fill the 3 red blanks function b=rev_rows(a)[n,m]=size(a); b=[]

//delete this line, finish the rev_rows function

endfunctionclc;printf("\n")a=[1,1,1,0;2,2,2,0;3,3,3,0]; disp(a);disp(rev_rows(a))

LOGICAL OPERATORS %t, %f are the logical or Boolean true and false values.If A and B are logical statements (i.e. either true or false) then

~ A is true iff A is false iff not A. A & B is true iff both A and B are true. A | B is true iff A or B or both are true.

is true iff .~x 0 x 0 is true iff .0 x & x 1 0 x 1 is true iff .x 0 x 0 x 0

Scilab prints %t, %f as T, F. Use the following yes_nofunction to print a truth value v as yes or no

EXAMPLE E8.1 yes_no This program converts the logical truthvalues T/F to the corresponding strings“yes” / “no”. //e8.1yes_no function ans=yes_no(v) if(v);ans="yes";else;ans="no";end endfunctionclc;for x= -.3:.1:.3 printf("\n Is %.2f negative?",x) printf(" %s",yes_no(x<0))

end

First solve problems by hand. Then write code. The powers of 3 are .30, 31, 32, 33, ... 1, 3, 9, 27, ...

CLASSWORK C8.2(3) is_power_3 Together. Write a functionis_power_3(n) which returns the truth value %t if n is apower of three, returns %f if not. Don’t use n^m, n**m. Read the For-loops paragraph about setting truth values.Copy lines, File/New in SciNotes, paste, File/Save as ...

//c8.2(3)is_power_3 fill the 3 red blanks function val=is_power_3(n)

//delete this line, write the is_power_3 function

endfunctionfunction ans=yes_no(v) if(v);ans="yes";else;ans="no";end endfunctionclc;for i=9:28; ans=yes_no(is_power_3(i))printf('Is %i a power of 3?, %s\n', i,ans)end

CLASSWORK C8.3(2) num_powers_3 Together. Write a functionnum_powers_3(m,n) which counts all numbers beweenand including m and n which are powers of 3. Test onnum_powers_3(1,400)Use is_power_3 but not ^ or **.

To count items, start the count at 0. Whenever an item is found, increase the count by 1.Copy lines, File/New in SciNotes, paste, File/Save as ...

//c8.3(2)num_powers_3

//replace this line with the is_power_3 function, no test lines

function k=num_powers_3(m,n)k= _____for i=m:nif ( _____ ) then

k= _____end

endendfunctionclc;k=num_powers_3(1,400)

printf('\nThere are %i powers <=400',k)

CLASSWORK C8.4(2) list_powers_3 Together. Write a functionlist_powers_3(m,n) which gives the vector listingnumbers between and including m and n which are powers of3. list_powers_3(2,10)= [3,9]. May not use ^ or **. Copy lines, File/New in SciNotes, paste, File/Save as ...

//c8.4(2)list powers_of_3 function a=list_powers_3(m,n)

//replace this line with the 6 lines inside num_powers_3 //replace the two k=... lines which count with a= ... lines which list powers

endfunctionclc; printf('\n')a=list_powers_3(1,400); n=length(a); printf('\n powers <=400: [') for i=1:n; printf(' %i',a(i)); end printf(']\n')

CLASSWORK C8.5(2) next_power_3 Together. Write a functionnext_power_3(n) which gives the first power of three after the input n, i.e., >n. Example: next_power_3(9)=27Copy lines, File/New in SciNotes, paste, File/Save as ...

//c8.5(2)next_power_of_3 next power 3>n

//replace this line with the is_power_3 function, no test lines

function p=next_power_3(n)p = _____ while (%t) if ( _____ ) then _____ else p = _____ endendendfunctionclc; printf('\n')for i=1:10:150; k=next_power_3(i);printf('Power of 3 after %3i = %4i\n',i,k);

end

CLASSWORK DUE AT END OF PERIOD

email to: [email protected] subject line: 190 c8(12) C8.1(3)rev_rows, C8.2(3)IS_power_3, C8.3(2)num_powers_3,

C8.4(2)list_powers_3, C8.5(2)next_power_3

LOCKED IN INFINITE LOOP When locked in an infinite loop, try in SciLab, pressing

<F2> or right-click in the SciLab window and select ClearConsole. Try selecting Control/Abort, try to close theSciLab window by clicking its x button. Otherwisesimultaneously press <alt-crtl-del>, then TaskManager, then select Scilab Console, then End Task.

HOMEWORK H8.1(3) rev_cols Write a function rev_cols(a)whose value b reverses the columns of matrix a. You are tomake a vector listing the reversed columns, not print columnsin reverse order. The function has no printf, no disp.

//h8.1(3)rev_cols function b=rev_cols(a)

//delete this line, write the rev_cols function

endfunctionclc;printf("\n")a=[1,2,3,4;1,2,3,4;0,0,0,0]; disp(a);disp(rev_cols(a))

The perfect squares are 02, 12, 22, 32, 42, ... 0, 1, 4, 9, 16...HOMEWORK H8.2(2) is_perfect_square Write a functionis_perfect_square(n) which returns the truth value %t

if n is a perfect square, returns %f if not. ReT the for-loopsparagraph about setting truth values. You may use i^2.

//h8.2(2)is_perfect_square fill the 3 red blanks function val =is_perfect_square(n)val = _____ //fill in the blankfor i=0:n

//delete this line, fill three more lines

endendfunctionfunction ans=yes_no(v) if(v);ans="yes";else;ans="no";endendfunctionclc; printf('\n')for i=8:25; v=yes_no(is_perfect_square(i));printf('Is %i a perfect square?, %s\n', i,v)

end

HOMEWORK H8.3(2) num_perfect_squares Write a functionnum_perfect_squares(m,n) which counts all numbersbeween and including m and n which are perfect squares.Include testing lines. Use is_perfect_square but not ^or **. //h8.3(2)num_perfect_squares

//replace this line with the is_perfect_square function, no test lines

function k=num_perfect_squares(m,n)//delete this line fill in the function num_perfect_squares

endfunctionclc; printf('\n') k=num_perfect_squares(0,26);//ans=6printf('\nThere are %i perfect squares <=26',k)

HOMEWORK H8.4(3) list_perfect_squares Write a functionlist_perfect_squares(m,n) which gives the vectorlisting numbers between and including m and n which areperfect squares. May not use ^ or **. Use the functionis_perfect_square but not its testing lines. You are towrite a function; no credit for just printing the values. Thefunction generates a vector; it does not print anything. Copy lines, File/New in SciNotes, paste, File/Save as ...

//h8.4(3)list_perfect_squares

//replace this line with the is_perfect_square function, no test lines

function a=list_perfect_squares(m,n) //delete this line fill in the list_perfect_squares function

endfunctionclc; printf('\n')a=list_perfect_squares(0,20); n=length(a) printf('\n perfect squares <=20: [') for i=1:n; printf(' %i',a(i)); end printf(']\n'); //ans: [0,1,4,9,16]

HOMEWORK H8.5(4) previous_perfect_square Write a functionprevious_perfect_square(n) which gives the firstperfect square before the input n, i.e., <n. Assume n is 1Example: previous_perfect_square(9)=4//h8.5(4)previous_perfect_square

//replace this line with the is_perfect_square function, no test lines

function p=previous_perfect_square(n)//delete this line fill in the previous_perfect_square function

endfunctionclc; printf('\n')for i=1:5:50 k=previous_perfect_square(i)printf('Perfect square before %3i = %4i\n',i,k)

end

HOMEWORK DUE BEFORE NEXT CLASS email to: [email protected] subject line: 190 h8(14)H8.1(3)rev_cols H8.2(2)is_perfect_square, H8.3(2)num_perfect_squares, H8.4(3)list_perfect_squares, H8.5(4)previous_perfect_square

190 Lecture 9 ProgrammingMIDTERM EXAM Feb. 16, 18. Covers Lectures 1-10. Nolaptops, no email, no internet access. USB drives allowed. Tuesday open book (notes, USB drives allowed). Thursday closed book (nothing allowed, quiz type problems).

Note: Imperative sentences are in green. They don’t carryinformation. Information is in the black declarativesentences. When looking for information or reviewing, skipthe green.

RECALL LOOP EXITS:break gets you out of the current loop. return gets you out of the function.continue starts a new iteration of the loop from the top.while(??) loops until ?? is true.

CLASSWORK C9.1(2) my_min Write a function my_min(v)which finds the value y of the minimum element of vector v. Don't use built-in min(y). Copy lines, File/New in SciNotes, paste, File/Save as.

//c9.1(2)my_min minimum elementfunction y= my_min(v)

//delete this line, finish the my_min function

endfunction; clc;printf('\n')a=[3,3,2,5];disp(a);disp(my_min(a)) //ans: k=2

a=[6,3,4,5,5];disp(a);disp(my_min(a)) //ans: k=3

CLASSWORK C9.2(2) num_divisors Write a function whichcounts the divisors of n. Copy lines, File/New in SciNotes, paste,File/Save as.

//c9.2(2)num_divisors number of divisors of nfunction k = num_divisors(n)

//delete this line, write the num_divisors function

endfunction; clc;printf('\n')for i=3:12; k=num_divisors(i); if (k==2); s="prime"; else; s="composite"; endprintf('%i has %i divisors, %s\n',i,k,s)

end

1 and n are the trivial divisors of n. n is composite if it hasa nontrivial divisor. If and has no nontrivial divisors, itn 2is prime. CLASSWORK C9.3(3) is_prime Write a function is_prime(n)which returns the truth value $t if n is prime and %f if not. Copy lines, File/New in SciNotes, paste, File/Save as ...

//c9.3(3)is_prime function val=is_prime(n) if(n<2); val=%f; return; end

//delete this line, finish the is_prime function

endfunction; clc;printf('\n')for i=2:12 if(is_prime(i));s="is prime";else s="";end printf('%i %s\n',i,s)

end

CLASSWORK H9.4(3) nth_prime Write a functionnth_prime(n) which gives nth prime number.nth_prime(1)=2, nth_prime(2)=3, nth_prime(3)=5, ...

nth_prime(10)=29. Let p range over possible primes. Let krange over their numbers.

//c9.4(3)nth_prime //replace this line with the is_prime function, no test lines

function p=nth_prime(n)//delete this line, finish the nth-prime function

endfunction; clc;printf('\n')for n=1:20 p=nth_prime(n); printf('prime #%3i = %4i\n',n,p)

end //2,3,5,7,11...

The percentage of numbers in which are prime = (the1...nnumber of primes in 1:n)/ n. By the Prime Number

Theorem, this is approximately for large n.1lnn

CLASSWORK C9.5(3) percent_primes Write a functionpercent_primes(n) which calculates the percentage ofnumbers in which are prime. This percentage is1...napproximately .1/ lnnCopy lines, File/New in SciNotes, paste, File/Save as ...

//c9.5(3)percentage_primes//replace this line with the is_prime function, no test lines

function y=percent_primes(n)//delete this line, write the percent_primes function

endfunction; clc;printf('\n')for n=20:20:100printf('%3i, percent prime: %4.2f 1/log: %4.2f ...\n',n,percent_primes(n),1/log(n))

end

RECALL LOGICAL OPERATORS %t, %f are the logical or Boolean true and false values. If A and B are logical statements (i.e. either true or false) then

~ A is true iff A is false iff not A. A & B is true iff both A and B are true. A | B is true iff A or B or both are true.

gcd(n,m), the greatest common divisor of n and m is thegreatest integer which divides both n and m. Thus gcd8, 9 1, gcd8, 6 2, gcd6, 9 3, gcd12, 6 6 lcm(n,m), the least common multiple of n and m is thesmallest positive integer which is a multiple of both n and m.

lcm3, 4 12, lcm6, 4 12, lcm6, 9 18, lcm12, 6 12

CLASSWORK C9.6(3) gcd Write a function gcd(n,m) whichcalculates the greatest common divisor of n and m. Copy lines, File/New in SciNotes, paste, File/Save as ...

//c9.6(3)gcd greatest common divisorfunction d=gcd(n,m) //greatest common divisor

//delete this line, write the gcd function

endfunction; clc;printf('\n')printf("\n 1=gcd(8,9) =? %i",gcd(8,9))printf("\n 2=gcd(8,6) =? %i",gcd(8,6))printf("\n 3=gcd(6,9) =? %i",gcd(6,9))

printf("\n 6=gcd(12,6)=? %i",gcd(12,6))

CLASSWORK DUE END OF THIS PERIOD

email to: [email protected], subject line: 190 c9(16)C9.1 (2)find_min, C9.2 (2)num_divisors, C9.3(3)is_prime, C9.4(3)next_prime,C9.5(3)percent_primes, C9.6(3)gcd

HOMEWORK H9.1(2) my_max Write a function my_max(v)which finds the index (position) of the (first) maximum elementof vector v. Don't use built-in max(y).

Copy lines, File/New in SciNotes, paste, File/Save as.

//h9.1(2)my_max function k = my_max(v)

//delete this line, write the my_max function

endfunction; clc;printf('\n')a=[3,3,2,5];disp(a);disp(my_max(a)) //ans: k=5

a=[6,3,4,5,5];disp(a);disp(my_max(a)) //ans: k=6

HOMEWORK H9.2(3) list_divisors Similar to num_divisors above.

Write a function divisors(n) which gives the vectorwhich lists the divisors of n . list_divisors(3)=[1,3]list_divisors(4)=[1,2,4]//h9.2(3)list_divisors the list of divisors of nfunction v=list_divisors(n)

//delete this line, write the list_divisors function

endfunction;clc;printf('\n') for i=3:12; v=list_divisors(i) if length(v)==2 then; s=" is prime"; else; s="";endprintf("%i%s has %i divisors:",i,s,length(v));

disp(v); end

HOMEWORK H9.3(3) is_composite Write a functionis_composite(n) which returns the truth value %t if n iscomposite and %f if not. //h9.3(3)is_composite function val=is_composite(n)

//delete this line, write the is_composite function

endfunction; clc;printf('\n')for i=2:12 if(is_composite(i));s="is composite";else s="";end printf('%i %s\n',i,s)

end

HOMEWORK H9.4(3) next_prime Write a functionnext_prime(n) which gives the first prime greater than n. Copy lines, File/New in SciNotes, paste, File/Save as ...

//h9.4(3)next_prime //replace this line with the is_prime function, no test lines

function p=next_prime(n) //delete this line, finish the next_prime function

endfunction; clc;printf('\n')for i=1:10 k=next_prime(i) printf('Next prime > %3i = %4i\n',i,k)

end

HOMEWORK H9.5(3) lcm Write a function lcm(n,m) which oninputs n,m, gives the least common multiple of n and m.Note: k is a multiple of n iff n is a divisor of k iff theremainder of k/n is 0 iff modulo(k,n)==0

//h9.5(3)lcm least common multiple function k=lcm(n,m) //least common multiple

//replace this line with the gcd function, modify appropriately.

endfunction ; clc;printf('\n')printf("\n 3=lcm(1,3) =? %i",lcm(1,3)) printf("\n 4=lcm(2,4) =? %i",lcm(2,4)) printf("\n 6=lcm(2,3) =? %i",lcm(2,3)) printf("\n 12=lcm(4,6) =? %i",lcm(4,6))

HOMEWORK DUE BEFORE NEXT CLASS. email to: [email protected] subject line: 190 h9(15)H9.1(2)my_max H9.2(3)list_divisors H9.3(4)is_composite H9.4(3)nth_prime H9.5(3)lcm

MIDTERM EXAM Feb. 17, 19. Covers Lectures 1-10. Nolaptops, no email, no internet access. USB drives allowed. Tuesday open book (notes, USB drives allowed). Thursday closed book (nothing allowed, quiz type problems)

190 Lecture 10 ProgrammingMIDTERM EXAM Feb. 17, 19. Covers Lectures 1-10. Nolaptops, no email, no internet access. USB drives allowed. Tuesday open book (notes, USB drives allowed). Thursday closed book (nothing allowed, quiz type problems)

CLASSWORK 10.1(3) grade Given a score x, a mean m and astd. dev. s, write a function grade(x,m,s) gives thescore’s letter grade which is

A if x is 2 std. dev. above the mean, B if x is between 1 std. dev. & 2 std. dev. above the mean,C if x is between 1 std. dev. below & 1 std. dev. above,D if x is between 1 std. dev. & 2 std. dev. below the mean,F if x is 2 std. dev. below the mean,

Resolve < vs. in favor of the student.Copy lines, File/New in SciNotes, paste, File/Save as ...

//c10.1(3)grade

function g=grade(x,m,s) if(m+2*s<=x) then; g='A' //space before thenelseif(m+s<=x & x<m+2*s) then; g='B'

//delete this line,finish the grade function

end endfunction m=50; s=13; clc; printf("\n")

for i=80:-5:20 printf(" %i %s\n", i,grade(i,m,s))end //1A, 3B, 5C, 3D, 1F

PASCAL'S TRIANGLE:

1 1 x 11 x 11 2 1 x 12 x2 2x 11 3 3 1 x 13 x3 3x2 3x 11 4 6 4 11 5 10 10 5 11 6 15 20 15 6 1

CLASSWORK C10.2(5) coef Write a function coef(n) whichgives the vector of coefficients of . Test on n=2,5,8x 1n

Copy lines, File/New in SciNotes, paste, File/Save as ...

//c10.2(5)coef coefficients of (x+1)^nfunction b=coef(n)

//delete this line, write the function coefendfunctionclc; printf("\n")printf("(x+1)^4 =")disp(coef(4)) //Ans:1,4,6,4,1

We represent a polynomial as a vector of the coefficients ofthe polynomial when it is written in reverse order, i.e., withascending powers and 0 for any missing powers. Hence

is written and is represented with thex2 1 1 0x1 1x2

coefficient vector p=[-1,0,1]. The degree n=2 of then 2polynomial p is one less than the length(p)=3 of its vector p.In general . Likewise p=[2,-1,0,1]n lengthp 1represents the polynomial of degree 3.px 2 x 0x2 x3

If a is a real number, the result of evaluating at a is px. This can be written as a dot product:pa 2 a 0a2 a3

2 a 0a2 a3 2,1, 0, 1. 1, a, a2, a3

2,1, 0, 1. a0, a1, a2, a3. In general, for 2,1, 0, 1. a^0, 1, 2, 3

with coefficient polynomialpx p0 p1x p2x2 ... pnxn

, p p0, p1, ..., pn pa p0, p1, ..., pn. a^0, 1, ..., n where . p. a^0 : n n lengthp 1

CLASSWORK C10.3(3) eval Suppose a is a real number andsuppose is the vector of coefficients ofp p0, p1, p2, ..., pna polynomial written inpx p0 p1x p2x2 ... pnxn

reverse order (ascending powers). Write a functioneval(p,a)which gives the result evaluating aty pa pxa. Copy lines, File/New in SciNotes, paste, File/Save as ...

//c10.3(3)eval eval(p,a)=p(a)function y=eval(p,a)

//delete this line, write the one-line function evalendfunction; clc; printf("\n")disp(eval([-1,0,1],3)) //Ans:-1+x^2 at 3 =8 disp(eval([1,1,1,1],1)) //Ans:1+x+x^2+x^3 at 1 =4

disp(eval([0,0,0,0],2)) //Ans:0+0x+0x^2+0x^3 at 2 =0

. Applying floor to numbers in givesn 0, 1 0, n 0, nintegers . Adding 1 gives integers in 0, 1, 2, ..., n 1

The formula is 1, 2, 3, ..., n k 1 floorn randCLASSWORK C10.4(3) rock_paper_scissors Write a functionrock_paper_scissors() which randomly, with equalprobability, prints rock, paper or scissors. Copy lines, File/New in SciNotes, paste, File/Save as ...

//c10.4(3)rock_paper_scissorsfunction me=rock_paper_scissors()

r='rock';p='paper';s='scissors'k = __ // fill the blank

//delete this line, finish the function rock_paper_scissorsendfunction; clc;printf("\n")for i=1:6; printf("\n"); for j=1:5 printf(" %s",rock_paper_scissors())end;end

CLASSWORK C10.5(3) rock_paper_scissors_game Write a functionrock_paper_scissors_game() which randomly, withequal probability, prints rock, paper or scissors. Copy lines, File/New in SciNotes, paste, File/Save as ...

//c10.5(3)rock_paper_scissors_gamefunction rock_paper_scissors_game()r='rock';p='paper';s='scissors';q='quit'while(%t)k = __ //copy from above functionv = __ //copy from above functionme = __ //copy from above function you=input("Enter r, p, s, or q to quit >")if you==q then; __ // fill the blankselseif ...

you==r&me==__| you==p&me==__| you==s&me==__ thenprintf(" You %s Me %s You win",you,me)

elseif ... me==r&you==__| me==p&you==__| me==s&you==__ then

printf(" You %s Me %s I win",you,me)else;

printf(" You %s Me %s __",you,me)end

end endfunctionclc;printf("\n");rock_paper_scissors_game()

CLASSWORK DUE AT END OF PERIOD

email to: [email protected] subject line: 190 c10(17) C10.1(3)grade C10.2(5)coef C10.3(3)eval C10.4(3)rock_paper_scissors C10.5(3)rock_paper_scissors_game

HOMEWORK 10.1(3) grade2 Write a function grade2(n) withinteger input which returns A if 9 < n B if 7 < n < 9 C if 3 < n < 7 D if 1 < n < 3 F if n < 1

The output should be as follows:

F0F1D2D3C4C5C6B7B8A9A10

//h10.1(3)grade2 //delete this line,write the grade2 function

clc;printf("\n");for n=10:-1:0 printf(" %i %s\n", n,grade2(n))

end //2A, 2B, 3C, 2D, 2F

HOMEWORK H10.2(2) my_sort Suppose v is a vector ofnumbers. Write a function my_sort(v)which gives vectorv listed in increasing order. If v=[2,1,5,4] thenmy_sort(v)=[1,2,4,5]. You may not use the builtinfunction mtlb_sort. Recall that v([i,j])=v([j,i}) swapselements at positions i,j.

//h10.2(2)my_sort sorts in increasing orderfunction v=my_sort(v) n=length(v) for i=1:n; for j=1:n if i<j & v(i)>v(j) then v([i,j])= __ // fill the blank end end;end;endfunction; clc;printf("\n")disp(my_sort([4,3,2,1])) //Ans:1,2,3,4disp(my_sort([5,0,5,5,0])) //Ans:0,0,5,5,5

HOMEWORK H10.3(3) coef2 Write a function coef2(n,a)which gives the vector of coefficients of , where a is ax an

constant. Note, withx y3 x3 3y1x3 3y2x1 1y3

Pascal’s coefficients 1, 3, 3, 1. x 23 x3 6x2 12x 8. The coefficient vector x3 321x3 322x2 123

1, 6, 12, 8 1, 321, 322, 23

120, 321, 322, 23 1, 3, 3, 1 . 20, 21, 22, 23 1, 3, 3, 1 . 2.^0, 1, 2, 3

. For coef, see classwork coef. For coef3 . 2.^0 : 3 we have n instead of 3 and a instead of 2 giving x an

coefn . a.^0 : n//h10.3(3)coef2 = coefficients of (x+a)^n

//replace this line with the classwork coef function

function c2 = coef2(n,a)

c2 = ___ // fill in the blank for coef2 endfunction; clc;printf("\n")disp(coef2(2,2)) //Ans:1,4, 4 disp(coef2(3,-2)) //Ans:1, -6,12, -8 disp(coef2(4,-1)) //Ans:1, -4, 6, - 4, 1

HOMEWORK H10.4(3) roll_die Suppose v is a vector ofnumbers. Write a function roll_die()which rolls a die. Itrandomly outputs 1,2,3,4,5,6 with equal probability. Seethe paragraph before rock_paper_scissors classwork.

//h10.4(3)roll_die random 1,2,3,4,5,6 function d=roll_die()d = __ // fill the blankendfunction; clc;printf("\n")for i=1:10; printf("\n"); for j=1:15; printf(' %i',roll_die()); end; end

HOMEWORK DUE NEXT CLASS email to: [email protected] subject line: 190 h10(11)10.1(3)grade2 10.2(2)my_sort H10.3(3)coef2 H10.4(3)roll_die

MIDTERM EXAM Feb. 17, 19. Covers Lectures 1-10. Nolaptops, no email, no internet access. USB drives allowed. Tuesday open book (notes, USB drives allowed). Thursday closed book (nothing allowed, quiz type problems)