1 / 33

Introduction

Introduction . >> t = 0:0.01:1 >> y = 2*pi*t >> x = sin(y) >> plot( t,x,t,y ) >> w = x'*x >> surf(w). Intro. MATLAB: Special Purpose Computer Program Optimized to perform engineering and scientific calculations Implements the MATLAB programming language

val
Download Presentation

Introduction

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction

  2. >> t = 0:0.01:1 >> y = 2*pi*t >> x = sin(y) >> plot(t,x,t,y) >> w = x'*x >> surf(w)

  3. Intro • MATLAB: Special Purpose Computer Program Optimized to perform engineering and scientific calculations • Implements the MATLAB programming language • Has an extensive library of predefined functions

  4. Advantages and disadvantages • Advantages: • Easy to use • Interpreted, not compiled • Integrated editor/debugger • Platform Independence • Works on Windows, Linux, Unix, and MacIntosh • Many predefined functions • E.g., arithmetic mean, standard deviation, median, etc. • Disadvantages: • Interpreted, not compiled • May execute more slowly

  5. Command Window • In command window, can type: • area=pi*2.5^2 • If line is too long , can add … to end of line to continue it on the next line • E.g., • x1 = 1 + ½ + 1/3 + ¼ + 1/5 + 1/6 • x1 = 1 + ½ + 1/3 + ¼ …+ 1/5 + 1/6 • Note the space between ¼ and …!

  6. Edit/Debug Window • Can create new Matlab files or modify existing ones • Created automatically when you create a new M-file or open an existing one • Select Home • Select New->Script (for scripts (nonfunctions)) • In edit window, type:%This m-file calculates the area of a circle.%and displays the result.radius = 2.5;area = pi * 2.5^2;string = [‘The area of the circle is ‘ num2str(area)];disp(string); • Save file as calc_area.m • Run by typing calc_area in Command Window • Select New->Function for functions

  7. Figure Windows • Used to display MATLAB graphics • Can be a two- or three-dimensional plot of data, an image, or a GUI • Write program to plot sin x: • %sin_x.m: This M-file calculates and plots the %function sin(x) for 0 <= x <= 6.x = 0:0.1:6y = sin(x)plot (x,y) • Save as sin_x.m and type sin_x into Command Window

  8. Getting Help in MATLAB • Use the Help Browser • ? Icon in desktop toolbar • Type "helpwin” in Command Window • Type “help” or “help” followed by function name in Command Window • “help” -displays a list of possible help topics • “help” function – displays help for that function • “lookfor” command • Searches summaries of each function for a match • Helpful in finding a function you don’t know the name of • E.g., suppose you wanted to find a function that takes the inverse of a matrix. • There’s no function called “inverse” • Do “lookfor inverse” • Get: • INVHILB Inverse Hilbert Matrix • ACOS Inverse cosine • ACOSH Inverse Hyperbolic cosine • ACOT Inverse Cotangent • ACSC Inverse cosecant • ACSCH Inverse Hyperbolic secant • ASIN Inverse sine • ASINH Inverse Hyperbolic sine • ATAN Inverse Tangent • Etc.

  9. Other Useful Commands • “demo” in command window (or select demos from the start button • Gives you demos of MATLAB’s capabilities • “clc” in command window • Clears content of command window • “clf” in command window • Clears content of figure window • “clear” in command window • Clears content of workspace • Good idea to avoid variables in one program affecting results in another program • Abort command (Ctrl-C) • Stops a running program • Good for infinite loops • “!” – sends commands to operating system and they are executed as if they’re typed into the operating system’s command prompt • Lets you embed op sys commands into MATLAB programs • “diary” filename • Once typed, all input and most output will be echoed into the diary file. • Helps find problems • To stop: type “diary off” • To continue: type “diary on”

  10. Matlabvs Python • Python Functions: def func(x): """ Summary of this function goes here Detailed explanation goes here """ return(x*x) • Matlab function [y] = func( x ) %Summary of this function goes here %Detailed explanation goes here y = x*x end

  11. Python vsMatlab Python: def func(): inp = input('would you like to continue?') totalcost = 0 while (inp =='yes'): totalcost = totalcost + 3 inp = input('Would you like to buy something else?') return(totalcost) Matlab: function [totalcost ]= func() inp = input('would you like to continue?','s'); totalcost = 0; while (strcmpi(inp,'yes') == 1) totalcost = totalcost + 3; inp = input('Would you like to buy something else?','s'); end end

  12. Python Vs Matlab arr = [3, 2, 8, 1, 4, 7, 9] k = len(arr) print(k) total = 0 for i in range (0,k): total = total + arr[i] print(total); Matlab: arr = [3 2 8 1 4 7 9] k = length(arr); disp(k) total = 0; for i=1:k %Note where loop starts!!! total = total + arr(i); end disp(total)

  13. Matlabvs Python arr = [3, 2, 8, 1, 4, 7, 9] k = length(arr) print(k) total = 0 for i in range (0,k,2): total = total + arr[i] print(total); Matlab: arr = [3 2 8 1 4 7 9] k = length(arr); disp(k) total = 0 for i=1:2:k %Note where loop starts!!! total = total + arr(i); end disp(total);

  14. Vectors In Matlab • A vector is a list of numbers expressed as a 1 dimensional array. • A vector can be n×1 or 1×n. • Columns are separated by commas (or spaces): h= [1, 2, 3] • Rows are separated by semicolons: v = [1; 2; 3]

  15. Matrices in Matlab Columns • A matrix is a two dimensional array of numbers. • For example, this is a 4×3 matrix: • m=[3.0, 1.8, 3.6; 4.6, -2.0, 21.3; 0.0, -6.1, 12.8; 2.3, 0.3, -6.1] Rows

  16. Defining (or assigning) arrays • An array can be defined by typing in a list of numbers enclosed in square brackets: • Commas or spaces separate numbers. • A = [12, 18, -3] or A = [12 18 -3] • Semicolons indicate a new row. • B = [2, 5, 2; 1, 1, 2; 0, -2, 6] • 12 18 -3 • 2 5 2 • 1 1 2 • 0 -2 6

  17. Array vs. Matrix Operations • Example: x = [2,1; 3,4] y = [5,6; 7,8] 2 1 5 6 3 4 7 8 z = x .* y results in [ 10, 6 21, 32] this is array multiplication z = x * y results in [ 17, 20; 43, 50] this is matrix multiplication So, do NOT forget the dot if you want to do array operations! (.* ./ .^)

  18. Matrix vs Array Multiplication • Multiply a .* b 10 15 4 36 • a * b 20 50 20 42 • b * c 11 16 • b .* c error • b * d • error • b .* d • error a = [ 10 5 2 9 ] b = [ 1 3 2 4 ] c = [ 2 3 ] d = [ 2 3 ]

  19. Defining arrays continued C = 12 18 -3 • 2 5 2 • 1 1 2 • 0 -2 6 • D = [C, C] • D = • 12 18 -312 18 -3 • 2 5 22 5 2 • 1 1 21 1 2 • 0 -2 60 -2 6 You can define an array in terms of another array: A = [12, 18, -3] B = [2, 5, 2; 1, 1, 2; 0, -2, 6] C = [A; B];

  20. Creating Zeros & Ones arrays • E = • 0 0 0 0 0 • 0 0 0 0 0 • 0 0 0 0 0 • F = • 1 1 1 • 1 1 1 • Create an array of zeros: E = zeros (3,5) • Create an array of ones: F=ones(2,3) Note: Placing a single number inside either function will return an n × n array. e.g. ones(4) will return a 4 × 4 array filled with ones.

  21. Retrieving Values in an Array • Index – a number used to identify elements in an array • Retrieving a value from an array:G = [1, 2, 3; 4, 5, 6; 7, 8, 9] G(2,1) G(3,2) • 1 2 3 • 4 5 6 • 7 8 9 • ans = 4 • ans = 8

  22. Changing Values in an Array • You can change a value in an element in an array with indexing: A = [12, 18, -3] • You can extend an array by defining a new element: • Notice how undefined values of the array are filled with zeros • A = • 12 5 -3 • A = • 12 5 -3 0 08

  23. Colon Operator • Colon notation can be used to define evenly spaced vectors in the form: first : last • The default spacing is 1, so to use a different increment, use the form: first : increment : last • The numbers now increment by 2 (Note: if we are incrementing by 1, we don’t need to specify) • H = • 1 2 3 4 5 6 • I = • 1 3 5 7 9 11

  24. Extracting Data with the Colon Operator • The colon represents an entire row or column when used as an array index in place of a particular number. • G = • 1 2 3 • 4 5 6 • 7 8 9 • ans = • 1 • 4 • 7 • ans = • 3 • 6 • 9 • ans = • 4 5 6

  25. Extracting Data with the Colon Operator Continued • The colon operator can also be used to extract a range of rows or columns: • G = • 1 2 3 • 4 5 6 • 7 8 9 • G = • 4 5 6 • 7 8 9 • ans = • 2 3

  26. Manipulating Arrays • The transpose operator, an apostrophe, changes all of an array’s rows to columns and columns to rows. • (how would you recreate J’?) J = 1 3 7 ans = 1 3 7

  27. function [ct] = BiSe(ls,n ) flag = 0; a = 1; b = length(ls); ct = 0; while (a <= b) && (flag == 0) x = floor((b - a)/2 + a); ct = ct + 1; if (ls(x) == n) %prints out the value of n, yep, and the value in ct fprintf('%d yep, %d counts \n',n,ct); flag = 1; elseif (ls(x) > n) b = x - 1; elseif (ls(x) < n) a = x + 1; end end if (flag == 0) %prints out the value of n, nope, and the value in ct fprintf('%d nope, %d counts \n',n,ct); end end

  28. Your job: • Write an algorithm (a detailed step-by-step description) of how you'd sort a list: ls = [32 1 6 88 63 23 45 26 2 17 82 9 4 42]

  29. Functions in Matlab • Selection Sort: function SS( arr) for i = 1:length(arr) smallest = i for j = i+1:length(arr) if arr(j) < arr(smallest) smallest = j; end end temp = arr(smallest); arr(smallest) = arr(i); arr(i) = temp; end disp(arr) End

  30. Function 2 • Bubble Sort: • function BuS( arr) • k = length(arr)-1; • flag = true; • while (k > 1) && (flag == true) • flag = false; • for i=1:k • if arr(i) > arr(i+1) • m = arr(i); • arr(i) = arr(i+1); • arr(i+1) = m; • flag = true; • end • end • k = k-1; • end • disp(arr); • end

  31. Function 3 • Insertion Sort: function IS(arr) for i = 1:length(arr) largest = arr(i); j = i – 1; while (j > 0) && (arr(j) > largest) arr(j + 1) = arr(j); j = j – 1; end arr(j+1) = largest; end disp(arr) end

  32. Making a class of students (in Python)? class Student(object): def __init__(self, lastname, firstname, testscores, labscores): self.lastname = lastname self.firstname = firstname self.testave = self.calcave(testscores) self.labave = self.calcave(labscores) def calcave(self,scores): tot = 0 for x in scores: tot += x return(tot//len(scores)) def printstudent(self): strvar = ""; strvar += self.firstname + " " + self.lastname + ": " strvar += "Test: " + str(self.testave); strvar += " Lab: " + str(self.labave); return(strvar) liststu = [Student("baker","tom",[99,77,82],[88,89,93,92,91]), Student("abbey","steven",[75,86,96],[82,76,88,91,93]), Student("lawrence","sarah",[99,92,93],[85,77,72,65,22]), Student("miller","john",[22,27,45],[77,78,66,72,12]), Student("jones","tina",[94,99,97],[99,98,99,96,91])] for x in liststu: print (x.printstudent())

  33. Sorting on Last name: def sortstudentslname(liststu): #is this a method or a function? for i in range(len(liststu)): smallstudent = liststu[i].lastname smallindex = i for j in range(i+1,len(liststu)): if liststu[j].lastname < smallstudent: smallstudent = liststu[j].lastname smallindex = j temp = liststu[i] liststu[i] = liststu[smallindex] liststu[smallindex] = temp return(liststu) liststu = [Student("baker","tom",132,88), Student("abbey","steven",122,96), Student("lawrence","sarah",144,85),Student("miller","john",132,92), Student("jones","tina",128,94)] for x in liststu: print (x.printstudent()) liststu = sortstudentslname(liststu) for x in liststu: print (x.printstudent()) Which sorting method is this one – how does it work?

More Related