lecture 1 arithmetic and functions

30
Lecture 1 arithmetic and functions 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 In Matlab, use ^ or ** for exponentiation. In Fortran, use only ** not ^. VARIABLES 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 a*b must use * for products, ab is two-letter variable name it is not a*b cost=1000*(1.05)^8 cost is a variable just like x, y, z ( )'S PRECEDENCE ^, then * and /, then + and -. Hence a*b^2-4*d = (a*(b^2))-(4*d) a*b/c*d = ? add ( )’s to remove unambiguity. (a*b)/(c*d) a*(b/c)*d a+b-c+d = ? rewrite with added ( )’s (a+b)-(c+d) a+(b-c)+d) Be able (on next time’s quiz) to calculate the following values: 1*2+3 1+2*3 2^2*3 2^(2*3) -2^2 (-2)^2 modulo(13,5) the remainder of 13/5, mod(13,5) in Fortran floor(13/5) no built-in quotient function but this works. ASSIGNMENTS AND EQUALITY TESTS. In math, means “x equals 2”. x 2 In MatLab, is the assignment command which sets x 2 x equal to 2 (any earlier value is lost). To test if x equals 2 in Matlab or Fortran, write . x= =2 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 value on right - increments value 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 3 x>=3 test if x 3 x~=3 test if (x/=3 in fortran, x!=3 in PHP, C) x 3

Upload: others

Post on 18-Dec-2021

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 1 arithmetic and functions

Lecture 1 arithmetic and functions

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 In Matlab, use ^ or ** for exponentiation.

In Fortran, use only ** not ^.

VARIABLES

a variables must be initialized a = 2a=2 spaces don’t matter a A Matlab is case sensitive, Fortran is not. b=3 a+b ab a*b must use * for products,

ab is two-letter variable name it is not a*b cost=1000*(1.05)^8

cost is a variable just like x, y, z ( )'S PRECEDENCE

^, then * and /, then + and -.Hence a*b^2-4*d = (a*(b^2))-(4*d)

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

(a+b)-(c+d) a+(b-c)+d)

Be able (on next time’s quiz) to calculate the following values:1*2+31+2*32^2*32^(2*3)-2^2(-2)^2modulo(13,5) the remainder of 13/5, mod(13,5) inFortranfloor(13/5) no built-in quotient function but this works.

ASSIGNMENTS AND EQUALITY TESTS.In math, means “x equals 2”. x 2In MatLab, is the assignment command which sets x 2

x equal to 2 (any earlier value is lost). To test if x equals 2 in Matlab or Fortran, write .x= =2

x variables must be initializedx=2x= =2 T = "True"x= =0 F = "False"x= =x+1 is always false. x=x+1 new value on left, old value on right - increments valuex+1=x wrong, need variable on the left, formula on rightx=input('Enter a number. > ') gets x fromkeyboardx<=3 test if x 3x>=3 test if x 3x~=3 test if (x/=3 in fortran, x!=3 in PHP, C)x 3

Page 2: Lecture 1 arithmetic and functions

CLASSWORK C1.0(3) Together. Write a functioneven_odd(n) which returns even if n is even, odd if not.Test it on 0, 1, ..., 9.//c1.0(3)odd(n) Test it on 0, 1, ..., 9.

Write functions in SciNotes, not in Scilab. Click Applications/SciNotes to open SciNotes. Copy the comment line // c1.0(3) ... as the first line. Write the function, Write lines which test it.

Select Execute ... file with echo or <ctrl-l>. Note the answers in the Scilab window. File/Save as c0.1(3), save in drive H: Once a function has been executed, you can use it inScilab. Go back to Scilab and enter: even_odd(0)

Pressing <F2> clears Scilab’s console window. To stop auto-completion in SciNotes, click “Preferences”and uncheck both “Auto completion” lines

PRINTING SUPPRESSION

x=0 x=1; x

To suppress printing to the monitor, end lines with “;”.

MULTIPLE COMMANDS PER LINE To enter several commands on the same line, separate

them with “;” (no printing) or “,” (printing). x=1, x=x+1, x=x^2 Homework prob. 2.1, 2.2

x=1; x=x+1; x=x^2 What is printed? (on the next quiz)

CONSTANTS AND BUILT-IN FUNCTIONSx=100%pi = =3.14 ...%e =2.716 ...log(x) =ln(x), the natural logarithmlog10(x) common base-10 logarithm sqrt(4) 4abs(-3) absolute value |-3| round(4.5) rounds to nearest integer (5 in this case). ceil(4.5) rounds up to nearest >= integer. >= means >floor(4.5) rounds down to nearest <= integer. <= means <factorial(3) = 3! = 3*2*1sin(%pi/2) angles are in radians, not degrees

The trig functions sin, cos, tan are in radians. Theirinverses: are also written arcsin, arcsin,sin1, cos1, tan1

arctan. In Matlab/Scilab they are written atan, asin,acos.rand()rand()rand() returns a random number between 0 and 1

COMMENTS

In Scilab // indicates a comment which Scilab ignores. In Matlab % precedes comments; in Fortran it is !. One of the next two lines gives an error.

log(%e) natural logarithm log(%e) //natural logarithm

HELP

To get help enter:help

To get help about matrices, enterhelp matrix

Page 3: Lecture 1 arithmetic and functions

MATLAB VARIABLES ARE INDEPENDENTx=2 f=2*x x=3 f //changing x doesn’t change f, it is a memory location.

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

variables). To make f a dependent variable that depends onx, define it as a function f(x).

Lecture 2 arithmetic and functionsDEFINING FUNCTIONS

Write a function vol_sphere(r) which gives the

volume of a sphere of radius r. Reminder, do this in4r3

3SciNotes. Go to the SciNotes window Select File/New (or <ctrl-n>). Copy/paste the next 4 lines to SciNotes (SciNotes, not

SciLab).

function V=vol_sphere(r) V=4*%pi*r^3/3; endfunction vol_sphere(6) //answer = 904.77868 --

Saving: click File/Save, enter a file name, click save.Entering vol_sphere makes a file vol_sphere.sce

To open this file in a later session, click File/Open,select the file name.

Select Execute ... file with echo or <ctrl-l>

Once a function has been executed, it may be used inScilab.Go to the Scilab window and enter vol_sphere(10) this gives the volume of a sphere of radius

10

Note: vol_sphere is the function name. V is the output variable.

To call the function, use the name, not the output variable.E.g., write vol_sphere(10), not V. b

WRITING HOMEWORK/CLASSWORK PROBLEMS.Work in SciNotes. For each problem: Select File/New (or <ctrl-n>), Paste the problem’s template comment into the file (e.g., “// c2.1(1) Function for ...”). Highlight the name “c2 1(2)”,<ctrl-c> to copy. Select File/Save (or <ctrl-s>) and paste in the file name.Make sure the directory is H: Add the needed Scilab code and test lines. Test using Execute/ ... with echo or <ctrl-l>. Save using <ctrl-s>.

Send all classwork problems in one email at the end of this period,Copy from SciNotes, not from SciLab.

CLASSWORK C2.1(2) len. Write a function len(x,y,z)which calculates the length of the vector x2 y2 z2

. Test it with len(0,0,3) x, y, zCopy lines, File/New in SciNotes, paste, File/Save as c2.1(2)len. //c2.1(2)len len(x,y,z) = length of [x,y,z]. mode(0);warning("off")//Test it on [0,0,3]

Page 4: Lecture 1 arithmetic and functions

CLASSWORK C2.2(2) vol_can. Define a 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). // c2.2(2)vol_can(r,h) = // volume of a can of radius r,height h.mode(0);warning("off") // Use it on a can of radius 10, height 4. // Answer: 1256.6371 .

CLASSWORK C2.3(2) toss() Together. Write a functiontoss() which tosses a coin giving H or T for heads ortails. Test it by tossing it a user-entered number of timeswith tosses in one row. Should get random H’s, T’s. Copy lines, File/New in SciNotes, paste, File/Save as c2.3(2)toss(). //c2.3(2)toss() tosses a coin returning H or T mode(0);warning("off") //Toss it n times where n is entered by theuser. c2.4(2). Together. Write a function f(x,n) whichcalculates

for any x , n. Test it on .x x2

2 x3

3 ... xn

n f 12, 3File/New in SciNotes, copy the lines, File/Save as c2.4(2)series //c2.4(2)series Function f(x) = x+x^2/2+... . mode(0);warning("off") // Test on f(12,3). Answer: 660.

CLASSWORK C2.5(2) factorial. Together. Write a functionmy_factorial(n) which calculates . Compare with then!builtin factorial(n) on n=10 When writing functions, youmay not use the builtin version.

for any x , n. Test it on .x x2

2 x3

3 ... xn

n f 12, 3Copy lines, File/New in SciNotes, paste, File/Save as c2.4(2)factorial // c2.5(2)factorial my_factorial(n) test onn=10

mode(0); warning("off")

HOMEWORK H2.1(2) vol_box. Write a Scilab functionvol_box(w,l,h) (in SciNotes, not SciLab) which calculatesthe volume of a box of height h, width w, length l. Includea line which uses it to calculate the volume of 3x3x2 box.Should be 4 lines, all entered in SciNotes.

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

HOMEWORK H2.2(4) series. Write a SciLab function g x, nthat calculates

for any x, n. 1 x x2 x3 ... xn

Add a line which tests on . gx, n x 12, n 3// h2.2(4) g(x,n)=1+x+x^2+x^3+ ... mode(0). // Test g(x,n) on x=12, n=3. Answer: 1885.

HOMEWORK H2.3(4) product Write a SciLab function h x, nthat calculates

for any x, n. x 1x 2x 3...x nTest it on . Fill in the one blank line. h2, 4//h2.3(4)product h(x,n)=(x+1)(x+2)...(x+n)mode(0);warning("off")//Test on h(2,4) Answer: 360.function y=h(x,n)y=1for i=1:n __________endendfunction

Page 5: Lecture 1 arithmetic and functions

Disp(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 15 times. Warning, no userinput as with the classwork problem.

//h2.4(2)tossbent() tosses bent coin that is // heads 75% of the timemode(0);warning("off")// Test function by tossing the coin 15 times.// Print tosses in one row.

If a title in SciNotes has a *, it hasn’t been saved,<ctrl-s> saves it.

Lecture 3 vectors and matrices

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

[1,2,3] matlab/scilab notation for row vectors[8]= =8 a=[2 3 4] separate entries with spaces or commasb=[10,10,10] a+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 muliplication[a,b] a followed on the right by b. , continues on right.[a;b] first row a, second row b. ; starts new row below.a(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]bb' transposebb=b', ba+b, b-a, a.*b operations are performed componentwise.[a,b] column a followed on the left by column b. [a;b] append b below a. Homework Prob. 2

Operations on vectors

sum(a) sum of entries , sum( [4;3;2] ) = 9prod(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.

ARITHMETIC PROGRESSIONS .

[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:5 abbreviation for [0:1:5][8:1:2][8:-1:2]for i=[3,1,5], disp(2*i), endfor i=3:5, disp(2*i), end

Page 6: Lecture 1 arithmetic and functions

Open SciNotes. Enter all homework in SciNotes (not in

Scilab). Don’t send Scilab answer lines. Don’t send attachments.

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

DOT (INNER) PRODUCT classwork problem 2.a, b, c a, b, c a a b b c c

= the dot product. This formula only works for vectors oflength 3. The dot_product function (built into Matlab butnot Scilab) must work for vectors of any length..

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)

endfunctiondot_product([1,2],[3,4]) //Answer 11dot_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.

function x=H(a) x=sum(a^3)endfunctiona=input('Enter a vector. > ')disp(H(a))

MAGNITUDE (GEOMETRIC LENGTH) a2 b2 c2

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

CLASSWORK C3.2(2) mag(a) Together. Define a functionmag(a) which calculates the geometric length of a. Afterthe function, write lines which get the vector a from theuser and displays mag(a). Copy lines, File/New in SciNotes, paste, File/Save as c3.2(3)mag(a)

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

mode(0);warning('off');printf('\n');

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

NOTATION. In Matlab we often write a1 or a_1 for .a1

Variable names may include characters, numbers orunderscores “_”. Start with an alphabetical character(required by Fortran but not Scilab).

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 distanceD=distance(a,b) between vectors a and b. Use it tofind the distance between [1,2] and [3,3] and thedistance between[1,2,3] and [3,3,3]. Your function mustwork for vectors of any length, it may not use +...+. See example e3.2above. Don't send answers. Try entering the formula one step-and-testat a time.

//h3.1(3)distance

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

Page 7: Lecture 1 arithmetic and functions

//Test on distance between [1,2,3],[3,3,3] Ans: 2.23

MATRICES AND MATRIX MULTIPLICATION Enter in SciLab:a=[1 2; 3 4] b=[1,1;1,1] 2*b,a+b, a-b, a.*b, a*b [n,m]=size(a) // n= number of rows, m= number columns

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 andthe jth column of the second matrix.

a=[1 2;3 5] 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] b[b,[0;0]] appends new column on the right[b;[0,0]] appends new row below

z=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 //home problem!

a(:,[2,1]) result of swapping columns 1,2

HOMEWORK H3.2(2) 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(2)swap swaps rows i, jmode(0);warning('off');printf('\n');function b=swap(a,i,j) b=a b([i,j],:)= ______________endfunction//Testing linesa=[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))

Identity matrix, matrix inversesb=ones(1,3) b=0*b b=8*ones(3,1)

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

1 is the identity for multiplication of numbers: .1x x1 x

I 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

Page 8: Lecture 1 arithmetic and functions

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.22D-16 2.22 1016 0Computer arithmetic isn’t always exact. 1/3 = .3333333333333333.... .333333

CLASSWORK C3.3 (2) id(n) Write a function id(n) whichgenerates the nxn identity matrix. For n=6, compare itwith the builtin identity function eye(2,2). Copy lines, File/New in SciNotes, paste, File/Save as c3.3(1)id(n)

//c3.3(1)id(n) = nxn identity matrix. mode(0);warning('off');printf('\n');// test id(n) and eye(n,n) on n=6. b

ELEMENTARY ROW OPERATIONS

Given a matrix, there are three types of elementary rowoperations: You mayv switch (permute) rows, v multiply a row by a nonzero constant, v add to a given row, a multiple of another row.

Lecture 4 vectors and matrices

HOMEWORK H4.1(4) countup(n) In SciNotes, write a Scilabfunction countup(n)which generates the nxn matrix

whose entries, when read in the row-column order are1,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.1(4)countup(n)mode(0)function a=countup(n)C=1for i=1:n, for j=1:n

a(i,j)= _____ //hint: single letterC = C+ _____ // hint: single digit

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

end

CLASSWORK C4.1(2) pos_count(a) Write a functionpos_count(a) which counts the number of positiveentries in the matrix a. Test with the given lines.Copy lines, File/New in SciNotes, paste, File/Save as c3.4(2)pos_count(a).//c4.1(2)pos_count(a)= # positive entriesmode(0);warning('off');printf('\n');

... write the function 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=2

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

CLASSWORK C4/2(2) pos_prod(a) Write a functionpos_prod(a) which finds the product of the positiveentries in the matrix a. Test with the given lines.Copy lines, File/New in SciNotes, paste, File/Save as c3.4(2)pos_prod(a).//c4.2(2)pos_prod(a)= # product of positive entries

Page 9: Lecture 1 arithmetic and functions

mode(0);warning('off');printf('\n');

... delete this line, write the function pos_prod(x) here

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

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

HOMEWORK H4.2(4) pos_sum(a) Write a functionpos_sum(a) which totals the positive entries in the matrixa. Test with these lines. mode(0)//h4.2(4)pos_sum(a) sum of positive entriesmode(0);warning('off');printf('\n');... write the function here, like classwork pos_prod(a) but instead of increasinga growing product, you add to a growing sum.

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))

CLASSWORK C4.3(3) coef(n) Write a function coef(n)which gives the vector of coefficients of . Test onx 1n

n=5Copy lines, File/New in SciNotes, paste, File/Save as c4.3(3)coef(n)

//c4.3(3)coef(n) = coefficients of (x+1)^nmode(0);warning('off');printf('\n');//test on coef(2). Answer: 1,2, 1 //test on coef(5). Answer: 1, 5, 10, 10, 5, 1 //test on coef(8). Answer: 1, 8, 28, 56, 70, 56, 28, 8, 1

ELEMENTARY ROW OPERATIONS

Given a matrix, there are three types of elementary rowoperations: You may v switch (permute) rows,

v multiply a row by a nonzero constant, v add to a given row, a multiple of another row.

CLASSWORK C4.4(2) pivot(a) Write a functionpivot(a)which uses elementary row operations to makethe first column the identity column [1;0;0; ...] . You mayassume a(1,1) is not 0.Copy lines, File/New in SciNotes, paste, File/Save as c4.4(2)pivot(a).

//c4.4(2)pivot(a) makes first column [1;0;0;...] mode(0);warning('off');printf('\n');

... delete this line, write the function here

//Test line a=[2,6;4,5]];

disp(a), disp(pivot(a)) //ans= [1, 3; 0, -7] a=[2,2,6; 4,5,6; 7,11,25];

disp(a), disp(pivot(a)) //ans= [1, 1, 3; 0, 1, -6; 0, 4, 4]

Page 10: Lecture 1 arithmetic and functions

HOMEWORK H4.3(4) pivot2(a) Write a Scilab functionpivot2(a)which uses elementary row operations to makethe second column the identity column [0;1;0;0;...] You mayassume a(2,2) is not 0. Fill in the two blanks.

//h4.3(4)pivot2(a) makes second column [0;1;0;...]mode(0);warning('off');printf('\n'); function b=pivot2(a) [n,m]=size(a) b=a b(2,:)= _____________for i=1:n if( i~=2) b(i,:)=b(i,:)- _____________ end end endfunction //Test linea=[1,1,3;0,1,-6;0,4,4];

disp(a), disp(pivot2(a)) //ans= [1, 0, 9; 0, 1, -6; 0, 0, 28] a=[2,2,4,4; 4,2,4,2;2,1,0,0;2,2,2,2]disp(a),disp(pivot2(a))

//ans=[-2,0,0,2;2,1,2,1;0,0,-2,-1;-2,0,-2,0]

190 Lecture 5 equations graphs integralsOpen MATH 190 in a browser; select Lecture 5 Double-click the SciLab icon. See Chapter 3, 10 of text fordetails.

SOLVING SIMULTANEOUS EQUATIONS. EXAMPLE e5.1 Solve Corresponding augmented matrix

2x 4y 2x 3y 3

a 2 4 21 3 3

Solution Reduced row echelon form:

x 3y 2

rrefa 1 0 30 1 2

In SciNotes, enter the augmented matrix, then rref(a).a=[2,4,2; 1,3,3]rref(a)// x=-3, y=2

Execute with <ctrl-l>. This produces 6 answer lines in

Scilab.Finally, after //, hand-write the general answer as acomment:

EXAMPLE E5.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 eachchoice of the arbitrary parameter z.

Finally, hand-write the general answer as a comment:a=[1,2,3,4 4,5,6,7 5,6,7,8] rref(a) // x=-2+x, y=3-2x, z is arb

CLASSWORK 5.1(2) rref

x 16y 4z 50x 12y 2z 30x 68y z 0

Page 11: Lecture 1 arithmetic and functions

Enter the augmented matrix line and the rref line in SciNotes, notScilab.

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

// c5.1(2)rref Two SciNote lines, plus comment. Don’t copy answers fromSciLab. ... fill in two lines here// x=1.49,y=______,z= ______ //Write answer in the blanks above, rounded to two decimal places.

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

Enter the augmented matrix line and the rref line in SciNotes, notScilab.

// h5.1(2)rref Two SciNote lines, plus comment. Don’t copy answers fromSciLab. ... fill in two line here// x=______,y=______, z=______ //Write answer in the blanks above, rounded to two decimal places.

ONE-VARIABLE FUNCTION GRAPHS

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

CLASSWORK C5.2(1) plotCopy lines, File/New in SciNotes, paste, File/Save as c5.2(1)plot.

// c5.2(1)plot Plot the following points.// (0,1), (1,2), (2,4), (3,3). clf //Clears the graph window. This clf is required.x =[ ] ///Vector of x coordinatesy =[ ] ///Vector of y coordinates

plot(x,y) //Scilab chooses the line styleplot(x,y+1,'g') //change g to r to make a red line.

GRAPHING FUNCTIONS

In Matlab are written, asin, acos,sin1, cos1, tan1

atan.

EXAMPLE 5.3 Graph sin(x)Copy lines, File/New in SciNotes, paste, File/Save as c5.3(1)plot. // plot sin from -pi to pi. // clf is requiredx=-%pi:0.01:%pi // ; is required y=sin(x) // ; is required plot(x,y)

The above four lines can be rewritten in one line:

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

CLASSWORK C5.3(1) plot

Change lines in example. File/Save as c5.3(1)plot. Plot arctan from -10 to 10

Reminder, start with clf add ; after the two vector lines.// c5.3(1)plot arctan from -10 to 10 . b

Graph user-defined functions as below replacingplot(x,y) with plot(x,f).In SciNotes, copy/FileNew/paste/ the lines below. <ctrl-l>

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

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

Plot this “bell-curve” function over the interval .3, 3

Page 12: Lecture 1 arithmetic and functions

Note, write a function as in the paragraph above, not just a formula asin the classwork above.

// c5.2(1) plot the function f(x)= %e^(-x^2) from -3 to 3 clffunction y=f(x) ... delete this line, finish the problem, don't forget the required ;

AREAS AND INTEGRALS 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 fab f x

must be a user-defined function.

EXAMPLE 5.4 Find 1 cos2 x

function y=f(x) // previous classwork continued y=1-(cos(x))^2;

endfunctionintg(-%pi,%pi,f) clf;plot(-%pi:0.01:%pi,f) // should get =3.14...

CLASSWORK C5.4(2) semicircle Together. Calculate the areaof the unit semicircle, the top half of . x2 y2 1For a circle of radius is 1, the area is r2 12 3.14. The 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. semicirclex 1 x2

Define the function . semicirclexUse the integral to get the upper semicircle area. Plot it between . x 1 and 1Copy lines, File/New in SciNotes, paste, File/Save as c5.4(2)semicircle.

// c5.4(2)semicircle Define the upper semicircle function.// Use intg to find the semicircle area.// Graph the semicircle.clf; mode(0) //must start with clfb

To approximate the integral, divide the line segment into equal-width segments. Above each segmenta, b

draw a rectangle whose height is the function’s value. Thesum of the (signed) areas of these rectangles is a Riemannsum. The smaller the rectangle width, the more accuratethe approximation.

Page 13: Lecture 1 arithmetic and functions

f(x)

a bCLASSWORK C5.5(3) 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 --see previous classworkf x 1 x2

Find the integral using your function my_intg(a,b) Find the integral using the built-in functionintg(a,b,f). Copy lines, File/New in SciNotes, paste, File/Save as c5.5(2)my_intg.

// c5.5(2)my_intg with Riemann sums. Ans: 1.57mode(0);warning('off');printf('\n'); function y=f(x) y=sqrt(1-x^2) endfunction function riemann_sum=my_intg(a,b) ... delete this line, write the function my_intg hereendfunction printf("My answer = %f\n", my_intg(-1,1) )printf("Scilab answer = %f",intg(-1,1,f) )

HOMEWORK H5.2(3) my_intg Define the function f x sin x

Plot it over 0,Find the integral using your function my_intg(a,b).

You need to have function code for f and function code for my_intg.Write your function and plot as in c5.5(3) as opposed to just plotting aformula as in c5.3(1)

Also find the integral with the built-in functionintg(a,b,f).// h5.2(3)my_intg(a,b) integral of sin(x) from 0 to pi , Ans: 2

COMMON ERRORS

The most common error for homework h6.2(2) isforgetting to insert the three “.” needed for pointwisemultiplication.

If you computer doesn’t seem to be doing anything,check your Scilab window, you may have forgotten the “;”which causes a printing overflow in Scilab requiring userinput of n or y.

190 Lecture 6 3D equations formattingTANGENT 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 thegraph. The slope m of the tangent is called the derivative off an x. It is written .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

line and the slope of the secant line approaches the slope

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

h

Page 14: Lecture 1 arithmetic and functions

Hence is approximately the tangentm f a h f a

hslope when 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 C6.3(3) tangent Together. Plot f x 1 x2

over . 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 tangentto f at and plot a green line tangent at 1, f 1

1/3, f 1/3Copy lines, File/New in SciNotes, paste, File/Save as c6.3(3)tangent

// c6.3(3)tangentclf; mode(0)function y=f(x) y = 1-x^2 endfunctionx = -2:.01:2; function y=tangent(a) ... delete this line, fill in functionendfunctionplot(x,f)plot(x,tangent(-1),'r')plot(x,tangent(1/3),'g')

HOMEWORK H6.3(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

FORMATTED PRINTING

The printf command can print values of variables in asentence or a table with formatting of your own choosing.

Page 15: Lecture 1 arithmetic and functions

%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. %s is a character string. %12s is a string (right-justified) in a field of 12 spaces. \n makes a new line.

CLASSWORK C6.4(1) format Format decimal to two decimalplaces.

// c6.4(1)format format decimal to 2 decimal placesmode(0)for i=1:5 printf(' -1/%i = %f \n',i,-1/i) end

CLASSWORK C6.5(4) format Open a new file, Copy/Paste/Save code as

c6.5(4). Together. Format with one line per person (add a new

line character \n). Make phone numbers strings. Make thecolumns line up (give all the character strings the same maximum

length). // c6.5(4)names names, phone numbersmode(0); warning('off'); //Reduce echoed verbiage, use ;name=['Tom','Dick','Harry']phone=[1234, 0002, 555-4321]for i=1:3; printf('Name: %s Phone:%i',name(i),phone(i))

end

HOMEWORK H6.4(5) print_matrix. Write a functionprint_matrix(a) which on a matrix a, prints the matrixwith column titles 1, 2, 3 at the top and row titles 1, 2, on

the left. Titles and numbers must be right-justified in theircolumn. The first column has fields of width 4, theremaining columns have width 6.

If a=[11 12 13; 21 22 23], the printout should be

1 2 3 1 11 12 13 2 21 22 23

Fill in the three blanks.Copy lines, File/New in SciNotes, paste, File/Save as ...// h6.4(5)print_matrix Fill in the three blank lines mode(0); warning('off');function print_matrix(a)[n,m]=size(a) // n=number of rows, m= #columnsprintf('\n');printf(' '); for j=1:m; printf('%6i',j); end;printf('\n');for i=1:n; ________________ ; //print row number - width 4

for j=1:m; ________________ ; //print ith matrix row entries width6 end ____________; //print a new line hereendendfunction

a=[11 12; 21 22; 31 32; 41 42]; print_matrix(a)a=[11 12 13 14; 21 22 23 24]; print_matrix(a)b

As always, before sending your email, highlight theentire email, copy/paste to Scilab and check that the entireemail runs without producing errors. Don’t attach graphs.

DISPLAYING DATA AND COMMENTS

Page 16: Lecture 1 arithmetic and functions

mode(0) stops echoing commands, no more --> lines.disp(a) displays a variable a without writing “a =”. Ituses the default formatting. To choose your ownformatting, you need printf. However disp can handlevectors and matrices of variable sizes; printf doesn’t.

BAR CHARTS

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

y =[1,2,1,1,4,0,0,3,3,2] // the unsorted list of answersmtlb_sort(y) =

[0,0,1,1,1,2,2,3,3,4] // the sorted list of answers values(y) = [0,1,2,3,4] // the list of values (no repetition)freq(y) =

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

EXAMPLE e7.1y =[1,2,1,1,4,0,0,3,3,2]mtlb_sort(y) // displays the sorted list y, but doesn't change y

y // To change y you must use an assignment.

y = mtlb_sort(y) y b

190 Lecture 7 Statistics

INSERT MODE / OVERTYPE MODE

In SciNotes, type something, asdfasdf. Move yourcursor to the beginning. Press the <insert> key. Typesome more, press <insert> again, type some more.

BAR CHARTS CONTINUED

The built-in function mtlb_sort gives the sorted list. The built-in function bar makes a bar graph from a list ofvalues and a list of frequences.

The functions values and freq are not built-in. Thecode for these functions is listed below. Paste this codeinto any program which uses values or freq.

function V=values(y) //lists values of y y_sorted = mtlb_sort(y); a=y_sorted(1); V=[a]; for j = 2:length(y_sorted) a = y_sorted(j); if a~=y_sorted(j-1) V=[V,a]; end end endfunction

function F=freq(y) //lists value frequencies y_sorted = mtlb_sort(y); a=y_sorted(1); F=[1]; for j = 2:length(y_sorted) a = y_sorted(j); if a==y_sorted(j-1) i=length(F); F(i)=F(i)+1; else F=[F,1]; end

Page 17: Lecture 1 arithmetic and functions

end endfunction

//Copy/paste these functions before any code which uses thesefunctions. These functions will not be on any quiz or closed-bookexam.

CLASSWORK C7.1(1) bar Make a bar graph. Write Scilabcode in SciNotes which sorts the values, clears anyprevious graph and makes a bar graph of

w= [3,5,7,5,2,3,3,5,5,4,4,4,9,7,7,2,2] .Copy lines, File/New in SciNotes, paste, File/Save as c7.1(1)bar. Copy/paste the values and freq functions before everything else.The example below is for a dataset y of values. You need to changethe red characters to solve your problem for the dataset w of values.

//c7.1(1)bar Sort w. List the values. List thefrequencies.mode(0);warning('off');printf('\n');//Draw a bar graph of w. //This example has 5 bars, yours has 6 bars.

// w= [3,5,7,5,2,3,3,5,5,4,4,4,9,7,7,2,2]//Copy the values and freq functions here. //After the two functions, copy these lines. //Change the red characters.clf;mode(0); y=[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. disp('The values:')disp(values(y)) // values(y) lists the values in order. disp('The frequencies:')disp(freq(y)) // freq(y) lists the frequencies.

bar(values(y),freq(y)) // don’t write bar(y). b

If you get 5 bars, you didn’t replace y with w. If you getan “undefined” error, you didn’t paste copies of thevalues/freq functions.

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, athird below and the rest is more than 1 std. dev. from the mean.

HISTOGRAMS Suppose the weights of UH students are 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)

of the group. This is a histogram.

Page 18: Lecture 1 arithmetic and functions

Fre

quen

c ey

>>

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

CLASSWORK C7.2(2) histogramCopy lines, File/New in SciNotes, paste, File/Save as ...

//c7.2(2)Histogram group size = 2.

mode(0);warning('off');printf('\n');

v=grand(1,100,'nor',130,20); //replace this line withnext// 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. 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 <ctrl-l> 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 differencebelow.

Change the std. dev. from 20 to 10 then <ctrl-l>. Change the std. dev. from 20 to 40 then <ctrl-l>.

Change two lines in the code above to make a histogramfor the data w = [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.

IF - THEN STATEMENTS

even_odd(n) (from Lecture 1, c1.0(2)) determines if aninteger n is even or odd. n is even iff it is divisible by 2 iffthe remainder of n divided by 2 is 0 iff

modulo(n,2)==0.

mode(0);warning('off');printf('\n');function s=even_odd(n)if (modulo(n,2)==0) then //then , outer ( ) areoptional s='even'else s='odd'endendfunction

Here is the definition of absolute value.

if y | x | then

y x if x 0y x if not

You must negate negative numbers to make them positive.Recall that is written x>=y .x y

HOMEWORK H7.1(3) my_abs Write your own functionmy_abs(x) which returns the absolute value of a number.May not use the built-in function abs.

//h7.1(3)my_abs - may not use the built-in abs(x)mode(0);warning('off');printf('\n');function y=my_abs(x) ...delete this line, fill in the functionendfunctionprintf('\n') //prints a blank linex = [13, -4, 0, -3, 55];

Page 19: Lecture 1 arithmetic and functions

for i=1:length(x) printf('|%i| =%i\n',x(i),my_abs(x(i)))end

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 andthe the average of the two middle values if the list has aneven number of values. If the list is [2,3,1], then thesorted list is [1,2,3] and the median is the middle value2. If the list is [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, ..., an. This is computed by the built-in function

a1a2...ann

mean.

CLASSWORK C7.3(2) my_mean Write your own functionmy_mean(a) which returns the average of the values of avector a. Recall sum(a) adds the elements of vector a;length(a) is the number of elements. May not use thebuilt-in function mean.

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

//c7.3(2)my_mean Find a vector's average. mode(0);warning('off');printf('\n');function m = my_mean(a) ...delete this line, fill in the functionendfunctiona=[3,2,4],printf(" mean=%.2f\n",my_mean(a)) //ans 2

a=[5,3,1,1,5],printf(" mean=%.2f\n",my_mean(a)) // ans3

Let m be the mean. The standard deviation of ann-element sample (a randomly selected subset of the entire

population) is Thea1m2a2m2...anm2

n1standard deviation of the entire population is

a1m2a2m2...anm2

n

HOMEWORK H7.2(3) stdev_pop Write your own Scilabfunction std_dev_pop(a) which computes thepopulation standard deviation of the values of a vector a.

The formula is where ma1m2a2m2...anm2

nis the mean value. Use built-in functions mean andlength to calculate m and n. Use it to find the std. dev. of[1,2,3] and [1,2,3,3].

//h7.2(3)stdev.pop = population stand. dev.. mode(0);warning('off');printf('\n'); // Add testing lines which apply it to [1,2,3] and [1,2,3,3] // Answers: .816... and .829...

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, floor(-.3)=-1 ceil(.3)=1, ceil(-.7)=0

If a is a list of values (a vector), and n=length(a), then1 is the first position,

Page 20: Lecture 1 arithmetic and functions

n=length(a) is the last position, 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 = the first position, 3 = the last position,

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

a(mid=a(2) = y = the 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 middlepositions are floor(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 middlepositions. a(mid1), a(mid2) are the items in these positions.

After the list has been sorted (use a=mtlb_sort(a)), the median is either the item a(mid) in the middle position (for

lists of odd length) or (for lists of even length) the average of thetwo middle items [a(mid1)+a(mid2)]/2.

CLASSWORK C7.4(1) odd_median Write odd_median(a)which computes the median of a list (i.e., vector) a of oddlength.

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

//c7.4(3)odd_median(a)= median of items in vector a.mode(0);warning('off');printf('\n'); function median=odd_median(a) ...delete these lines, define n with length(a), sort a using mtlb_sort(a) ...middle position= mid=(1+n)/2 ...median = value at mid = a(mid)

endfunctiona=[30,10,20]printf("median=%i\n",odd_median(a)) //ans 20 a=[40 50 20 10 40]printf("median=%i\n",odd_median(a)) //ans 40

CLASSWORK C7.5(3) even_median Write even_median(a)which computes the median of a list (i.e., vector) a of evenlength.Copy lines, File/New in SciNotes, paste, copy lines from odd_median, file/save

//c7.5(3)even_median(a)= median of items in vector a.mode(0);warning('off');printf('\n');function median=even_median(a) ...delete these lines, reuse lines for odd_median, use floor, ceilendfunctiona=[40,20,50,10]printf("median=%i\n",even_median(a)) //ans 30 a=[40 50 20 10 0 60]printf("median=%i\n",even_median(a)) //ans 30

HOMEWORK H7.3(3) my_median Write a functionmy_median(a) which computes the median of a list (i.e., avector) a of values. Apply it [4, 2, 3] and [4, 2, 3, 4]. Copy the classwork functions odd_median, even_median into the file.Use n=length(a) to calculate the length of the list. Use modulo(n,2) to determine if the length is even or odd. Apply even_median if n is even, odd_median if n is odd.For full credit, you must write your program as above, don't just use the built-in function

median or just the function even_median (which actually works for the odd case).

//h7.3(3)my_median(a)= median of items in vector a.mode(0);warning('off');printf('\n');//Apply it to [4,2,3], [4,2,3,4] //Answers: 3 and 3.5

Page 21: Lecture 1 arithmetic and functions

HOMEWORK H7.4 (3) reverse_sort Write a functionreverse_sort(a) which sorts a matrix in descendingorder. Negate a, apply mtlb_sort, then negate again.Add lines which test the function on vectors of length 3and 4.

//h7.4(3)reverse_sort.mode(0);warning('off');printf('\n');

190 Lecture 8 logic

CLASSWORK C8.1(2) matrix_printer Together. Print a matrix a withright-justified columns and 2 decimal-place reals in 6-place fields. This is a

simple version of h6.4(5).

// c8.5(2)matrix_printer(a) mode(0);warning('off');printf('\n');function matrix_printer(a) //note, no returned value ...delete this line, write the function hereendfunctiona=[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 C8.2(2) row_sum Together, one step and test at atime. Write a function row_sum(a) which given a matrixa of reals, adds a new column on the right. Each item ofthe new column is the total of the row preceding it. Applythis function, row_sum, to this matrix aa=[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];

Use matrix_printer to print the resulting matrix.

The result, printed by matrix_printer should be 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

//c8.2(2)row_sum(a) use the matrix a above. mode(0);warning('off');printf('\n');

HOMEWORK H8.1(4) column_average Write a functioncolumn_average(a) which given a matrix a of reals, addsa new row at the bottom. Each item of the new row is theaverage (mean) of the column above it. Apply thisfunction, column_average, to this matrix aa=[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];Use matrix_printer to print the resulting matrix.The result, printed by matrix_printer should be 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 1.00 0.50 0.50 10.00

Warnings: writing a program which just prints the linesabove is easy to do, it will get you 1 point. For full credit,write you must write the requested functioncolumn_average. This function has no print statements.All printing is done using matrix_printer. To usematrix_printer, you must include its code in the file.

//h8.1(4)column_average(a) use the matrix a above.

Page 22: Lecture 1 arithmetic and functions

mode(0);warning('off');printf('\n');

HOMEWORK H8.2(2) ROW_column Fill in the blank lines asdirected to get a function row_column(a) which given amatrix a adds a column on the right with row totals (userow_sum to do this) and then adds a row at the bottom withcolumn averages (use column_average to do this) and finallyprints the result (use matrix_printer to do this).

//h8.2 (2)column_average(a) use the matrix a above. mode(0);warning('off');printf('\n'); ...delete this line, put matrix_printer code here ...delete this line, put row_sum code here ...delete this line, put column_average code herefunction row_column(a) //note, no returned valuea = ____________ a = ____________ matrix_printer( _____ )

endfunction a=[ 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]; row_column(a)

HOMEWORK H8.3(4) my_transpose Write a functionmy_transpose(a) which returns the transpose of a. Youdon’t get to use 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]. Ans: a'=[1,3,5; 2,4,6], b'=[1,4; 2,5;3,6].

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_no,true_false functions to print a truth value v as yes/no ortrue/false

EXAMPLE E8.1 true_false This program converts the logicaltruth values T/F to the corresponding strings “yes”/”no”.

//c8.3(2)true_false mode(0);warning('off'); function ans=true_false(v) if(v);ans="true";else;ans="false";end endfunctionfor x= -.3:.1:.3 printf("\n Is %.2f negative?",x) printf(" %s",true_false(x<0));

end

CLASSWORK C8.3(2) yes_no Modify the example to convertthe logical values T/F to the strings “yes” / “no”.

FOR-LOOPS

For-loops calculate counts, sums, products, lists, logicalor’s, logical and’s. The loop takes care of increasing a

Page 23: Lecture 1 arithmetic and functions

count, adding to a sum, or finding a logically true or falsecase. Start with what the answer will be if the for-loopfinds nothing.

Counts and sums start with 0, which is what the count orsum is if the loop finds nothing. Products start with 1. Alist a of items starts with the empty list [ ] which is thecorrect answer if nothing is found. When something i isfound, add it to the list: a=[a,i]. If the loop takes care ofsetting a truth value v true, %t, start with false, v=%fwhich is the correct answer until the loop sets it to true. Ifthe loop takes care of setting the answer to true, %t, startwith %f which is the correct answer until the loop sets itto true.

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.

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

CLASSWORK C8.4(3) is_power_of_3 Write a functionis_power_of_3(n) which returns the truth value %t if nis a power 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.4(2)is_power_of_3 fill the 3 red blanks mode(0);warning('off');printf('\n');

function v=is_power_of_3(n) ...delete this line, write the function hereendfunctionfunction ans=yes_no(v) if(v);ans="yes";else;ans="no";endendfunctionfor i=9:28; ans=yes_no(is_power_of_3(i));printf('Is %i a power of 3?, %s\n', i,ans)

end

b

The perfect squares are 02, 12, 22, 32, 42, ... 0, 1, 4, 9, 16...HOMEWORK H8.4(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. Read theFor-loops paragraph about setting truth values.

//h8.4(2)is_perfect_square fill the 3 red blanks mode(0);warning('off');printf('\n');function v =is_perfect_square(n) ...delete this line, write the function hereendfunctionfunction ans=yes_no(v) if(v);ans="yes";else;ans="no";endendfunctionfor i=8:25; v=yes_no(is_perfect_square(i));printf('Is %i a perfect square?, %s\n', i,v)

end

CLASSWORK C8.5(2) powers_of_3 Write a functionpowers_of_3(m,n) which gives the vector listingnumbers between and including m and n which are powersof 3. powers_of_3(2,10)= [3,9]. May not use ^ or **.Use the function is_power_of_3 but not its testing lines. Copy lines, File/New in SciNotes, paste, File/Save as ...

Page 24: Lecture 1 arithmetic and functions

//c8.5(2)powers_of_3 fill the 3 red blanks

mode(0);warning('off');printf('\n'); ...replace this line with the is_power_of_3 function, no test lines function a=powers_of_3(m,n) a= _____ ; for i= m:n; if ( _____ ) then a= _____ ; end end endfunction a=powers_of_3(1,400); n=length(a); printf('\n powers <=400: ['); for i=1:n; printf(' %i',a(i)); end printf(']\n');

HOMEWORK H8.5(3) perfect_squares Write a functionperfect_squares(m,n) which gives the vector listingnumbers between and including m and n which are perfectsquares. 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. //c8.5(3)perfect_squares

mode(0);warning('off');printf('\n'); ...replace this line with the is_perfect_square function, no test lines

function a=perfect_squares(m,n) ...delete this line fill in the functionendfunctiona=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]

CLASSWORK C8.6(2) count_powers_of_3 Write a functioncount_powers_of_3(m,n) which counts all numbersbeween and including m and n which are powers of 3. Teston count_powers_of_3(1,400)Use is_power_of_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.6(2)count_powers

mode(0);warning('off');printf('\n'); ...replace this line with the is_power_of_3 function, no test lines function k=count_powers_of_3(m,n)k= _____for i=m:n;if ( _____ ) then

k= _____end

endendfunctionk=count_powers_of_3(1,400);

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

HOMEWORK H8.6(2) count_perfect_squares Write a function count_perfect_squares(m,n)

which counts all numbers beween and including m and nwhich are perfect squares. Include testing lines. Useis_perfect_square but not ^ or **.

//h8.6(2)count_perfect_squares

mode(0);warning('off');printf('\n'); ...replace this line with the is_perfect_square function, no test lines

function k=count_perfect_squares(m,n)...delete this line fill in the functionendfunction

Page 25: Lecture 1 arithmetic and functions

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

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.

190 Lecture 9 ProgrammingNote: Imperative sentences are in green. They don’t carryinformation. Information is in the black declarativesentences. When looking for information, skip the green.

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

<F2> or right-click in the SciLab window and selectClear Console. Try selecting Control/Abort, try toclose the SciLab window by clicking its x button.Otherwise reboot: simultaneously press<alt-crtl-del>, then Task Manager, then selectScilab Console, then End Task.

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) next_power_of_3 Write a functionnext_power_of_3(n) which gives the first power ofthree after the input n. Example:next_power_of_3(9)=27Copy lines, File/New in SciNotes, paste, File/Save as ...

//c9.1(2)next_power_of_3 next power of 3 > nmode(0);warning('off');printf('\n');

...replace this line with the is_power_of_3 function, no test linesfunction y=next_power_of_3(n)p= _____ while (%t) if ( _____ ) then y= _____; _____ end p = _____endendfunctionfor i=1:10:150; k=next_power_of_3(i);printf('Power of 3 after %3i = %4i\n',i,k);

end

HOMESWORK H9.1(4) previous_perfect_square Write a functionprevious_perfect_square(n) which gives the firstperfect square before the input n. Assume n is 1Example: previous_perfect_square(9)=4//h9.1(2)previous_perfect_squaremode(0);warning('off');printf('\n');

...replace this line with the is_perfect_square function, no test linesfunction y=previous_perfect_square(n)...delete this line fill in the functionendfunctionfor i=1:5:50; k=previous_perfect_square(i);printf('Perfect square before %3i = %4i\n',i,k);

Page 26: Lecture 1 arithmetic and functions

end

To count items, start the count at 0, c=0. When an item is found, increase the count by 1, c=c+1.

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 Count the number of divisors ofnmode(0);warning('off');printf('\n');function c = num_divisors(n)

...delete this line, write the functionendfunction 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

HOMEWORK H9.2(4) divisors Similar to num_divisors above.

Write a function divisors(n) which gives the vectorwhich lists the divisors of n . divisors(3)=[1,3], divisors(4)=[1,2,4]

//h9.2(4)divisors get the list of divisors of n

mode(0);warning('off');printf('\n');

function a=divisors(n)...delete this line, write the function

endfunction for i=3:12; a=divisors(i);printf("%i has %i divisors: ",i,length(a));

disp(a); end

1 and n are the trivial divisors of n. n is composite if ithas a nontrivial divisor. If and has no nontrivialn 2divisors, it is prime.

CLASSWORK C9.3(3) is_prime Write a SciLab functionis_prime(n) which on input n returns the truth value $tif n is prime and %f if not.

//c9.3(3)is_prime mode(0);warning('off');printf('\n');function v=is_prime(n) if(n<2);v=%f;return;end

...delete this line, finish the functionendfunction for i=2:12; if(is_prime(i));s="is prime";else s="";end printf('%i %s\n',i,s);

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 mode(0);warning('off');printf('\n');function v=is_composite(n) ...delete this line, write the functionendfunction for i=2:12; if(is_composite(i));s="is composite";else s="";end printf('%i %s\n',i,s);

end

CLASSWORK C9.4(2) next_prime Write a functionnext_prime(n) which gives the first prime greater thann.

Page 27: Lecture 1 arithmetic and functions

//c9.4(2)next_prime mode(0);warning('off');printf('\n');

...replace this line with the is_prime function

function y=next_prime(n) ...delete this line, write the function

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

end

HOMEWORK H9.4(4) 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 primes. The firstprime is p=2; next_prime gets you from one prime tothe next. //h9.4(4)nth_prime fill in the missing lines:nth_primemode(0);warning('off');printf('\n');

...replace this line with the is_prime and next_prime functions function p=nth_prime(n)p= _____ // fill the blank (read paragraph above),for i=2:np= _____ // fill the blank (read paragraph above)

endendfunctionfor n=1:10; 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 =1...n(the number 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.1...n

//c9.5(3)pecentage_primesmode(0);warning('off');printf('\n');

...replace this line with the is_prime function

function x=percent_primes(n)...delete this line, write the function

endfunctionfor 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 andm.

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

CLASSWORK C9.6(4) gcd Write a function gcd(n,m)which calculates the greatest common divisor of n and m.

Page 28: Lecture 1 arithmetic and functions

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

// c9.6(4)gcd greatest common divisormode(0);warning('off');printf('\n');function y=gcd(n,m) //greatest common divisor

...delete this line, write the functionendfunction 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))

HOMEWORK H9.5(4) lcm Write a function lcm(n,m) whichon inputs n,m, gives the least common multiple of n andm. // h9.6(4)lcm least common multiplemode(0);warning('off');printf('\n');function y=lcm(n,m) //least common multiple ... delete this line, paste in lines from the gcd function, modify appropriately. endfunction

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))

190 Lecture 10 Programming

CLASSWORK 10.1(2) grade Given a score x, a mean m anda std. dev. s, grade(x,m,s) gives the score’s letter gradewhich 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 themean,

F if x is 2 std. dev. below the mean, Resolve < vs. in favor of the student.

//c10.1(2)grade mode(0);warning('off');printf('\n');

function g=grade(x,m,s) if(m+2*s<=x) then; g='A'elseif(m+s<=x & x<m+2*s) then; g='B' ...delete this line,finish the functionendendfunctionm=50; s=13;

for i=80:-5:20 printf(" %i %s\n", i,grade(i,m,s))end

HOMEWORK 10.1(3) grade2 Write a function grade2(n)with integer 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:

D2D3C4C5C6B7B8A9A10

Page 29: Lecture 1 arithmetic and functions

F0F1

//h10.1(3)grade2 mode(0);warning('off');printf('\n'); ...delete this line,write the functionfor n=10:-1:0 printf(" %i %s\n", n,grade2(n))

end

CLASSWORK 10.2(2) reverse Let list be a vector of nintegers. Write a function reverse(list) which returns theresult of listing the elements of list in the reverse order.If list=[4,2,3,1], thenreverse(list)=[1,3,2,4].

//c10.2(3)reverse

mode(0);warning('off');printf('\n');

...delete this line,write the functiona=[1 2 3], reverse(a), a=[5 4 3 2], reverse(a)

CLASSWORK 10.3(3) insert Let list be a vector ofintegers. Write a function insert(list,k,x) which,given k in 1:n inserts the number x into position k andpushes the existing records from k to n down to positionsk+1 and n+1.

Inserting a x=9 at position k=2 in the list on the left,should give the list on the right.

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

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

list(6)= 4

//c10.3(3)insert

mode(0);warning('off');printf('\n');

...delete this line,write the functionlist=1:5for k=1:6; printf("\nInsert 10 at position %i",k)

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

HOMEWORK 10.2(4) delete Let list be a list of n integers.Write a function delete(list,k) which, given k in 1:ndeletes the kth element of list and moves any elementsbelow the kth position up to any gap in the list to give avector of length n-1.

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

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

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

//h10.2(4)delete

mode(0);warning('off');printf('\n');

...delete this line,write the functionlist=1:5;for k=1:5 ; printf("\nDelete at position %i ",k); disp(list);disp(delete(list,k));

end;

Page 30: Lecture 1 arithmetic and functions

CLASSWORK 10.4(3) find_first Let list be a list of nintegers and let i be an integer which may or may not be inthe list. Write a function find_first(list,x)whichfinds the first position of x in the list. If x is not in the list,return 0.find([7,7,5,5],1)=0 find([7,7,5,5],7)=1 find([7,7,5,5],5)=3

//c10.4(3)find

mode(0);warning('off');printf('\n');

...delete this line,write the functionlist=[5 5 6 6 7 7]for k=4:8 printf("Item sought=%i",k) printf(" First position found=%i \n",find(list,k))

end

HOMEWORK 10.3(3) find_last Let list be a list of nintegers and let i be an integer which may or may not be inthe list. Write a function find_last(list,x)whichfinds the last position of x in the list. If x is not in the list,return 0. find_last([7,7,6,5],1)=0 find_last([7,7,6,5],7)=2 find_last([7,7,5,5],5)=4

//h10.3(3)find_last

mode(0);warning('off');printf('\n');

...delete this line,write the functionlist=[5 5 6 6 7 7]for k=4:8 printf("Item sought %i",k) printf(" Last position %i \n",find_last(list,k))

end