Lecture 4

Lecture 4 - Lecture 4. Creating Functions and...

Info iconThis preview shows page 1. Sign up to view the full content.

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

Unformatted text preview: Lecture 4. Creating Functions and Plotting Welcome to lecture 4 of Matlab. Today we will invest some time on the fun part of Matlab, creating your own functions and graphing them. This lecture will cover the following topics:  ­ create user ­defined functions  ­ plotting Create User ­Defined Functions Remember the .m (script) files we created in Lecture 1? These scripts simply execute some commands and operate on the current Workspace. We can also write our own function that takes one or more arguments and return a value. A function operates on its own workspace, thus we have to pass a value to it. We begin creating a function the same way we create a script, by typing: >>edit function_name to open the script/function window. Note: We have used the words “script” and “function” interchangeably before. From now on, we will make the distinction where “script” will only refer to script files that will operate on the current Workspace and “functions” will only refer to function files that operate on their own Workspace. Both a “script” file and a “function” file end with an .m in their name. The first line of the function window must begin with a declaration that it’s a function and its input and output variables. The name of the file and the name of the function should be the same. Example: Here is a function that takes an input and returns the square of it. squaref.m function y = squaref(x) % This function take a value and return the square of it. y= x .^ 2; Command Window: >>squaref(3) ans = 9 The first line “function y = SquareF(x)” says: this is a function called SquareF. It will take an input called “x” and it will give the value of “y” as the output. The second line “y = x.^2” says that y is equal to x squared. When we run the file, we supply an input, 3, and we get an output, 9. We use the .^ instead of just “^” because the function may also operate on matrices instead of scalars Note: Look at your Workspace, the variable “y” is not there. A function works in its own Workspace unlike a script. Therefore, you must provide ALL of the necessary the variables to the function as input arguments. You cannot access the variable “y” outside of the function itself. Exercise: Create a function called “quadratic” that takes the inputs “a”, “b”, and “c” from the equation ax^2 + bx + c = 0 and display the result of the two roots using the disp() function. The function should also return the two roots as a return value. The function should output the following: Command Window: >> quadratic(1,  ­3,  ­10); The first root of the equation is 5 The second root of the equation is  ­2 Quadratic.m function [x1, x2] = quadratic(a,b,c) % Take the input a, b, c from ax^2 + bx + c =0 % and output the two roots. The num2str() function is % used to convert a number into a string so we can concatenate % it with the string. The disp() function is then used to % display the output in one line. x1 = (-b + sqrt(b^2 - 4*a*c))/(2*a); x2 = (-b - sqrt(b^2 - 4*a*c))/(2*a); str1 = [ 'The first root of the equation is ', num2str(x1)]; disp(str1) str2 = [ 'The second root of the equation is ', num2str(x2)]; disp(str2) Notice that this function returns two values. In order to save both values, you must assign the output of Quadratic() into a matrix like the following: >> [X1,X2] = Quadratic(1, ­3, ­10) The first root of the equation is 5 The second root of the equation is  ­2 X1 = 5 X2 = Anytime you want to exit a function when a certain condition is reached, use the return statement. To use the return statement, you would want something like the following in your program: if (condition) return end Big O Recall the big_o script from the last homework assignment. Here we will informally introduce the concept of Big O. Big O is a concept in computer science that is used to describe the behavior of a function when the argument grows to a large number. Specifically, Big O is use to compare the efficiency of certain algorithms by providing the upper bound of the growth rate of the function. We express Big O using the O(some_function_of_n) notation where n is dependent on the size of the array. Take the following linear search algorithm for example: % A basic linear search algorithm that returns the location % of the element x in the matrix A. If element x does not % exist in A, the value 0 is returned. function i = linearSearch(A, x) i = 1; while ( i <= length(A) ) if (x == A(i)) return end i = i+ 1; end i = 0; What is the Big O of this algorithm? This algorithm grows in linearly time, and depends on the size of the array. The Big O of this algorithm is O(n) where n is the size of the array. There are other algorithms that grows at speeds such as O(n log n), O(n^2), and O(log n). You will see examples of this in the assignments. Please do not worry if you don’t understand what Big O, upper bounds of functions, and function growth means. This is only meant to be a simple introduction to the concept of Big O. A sample picture of the different Big O: Introduction to Plotting: Matlab not only is a powerful matrix calculator, it is also a powerful graphing calculator. Let’s generate our first graph: >> x = 0:pi/20:2*pi; y = sin(x); plot(t, y); xlabel('X Axis') ylabel('Plot Y Axis') title('Plot of Sin(x)') Lets go through the steps one by one: >> x = 0:pi/20:2*pi; First we generate our t values, which will be used to compute the y ­values. Here we are generating 20 t ­values from 0 to 2π. >>y = sin(x); Next we compute the y ­values by calculating the sin of the t ­values. >>plot(x y); Now we call the plot function, plot(x,y) to generate our graph >> xlabel('X Axis') >> ylabel('Plot Y Axis') The two commands above sets the x and y label of the graph. >> title('Plot of Sin(x)') And lastly, we set the title of our graph to “Plot of Sin(x)” Note: At anytime, we can change the x ­label, y ­label, and the title of our plot by simply calling the corresponding commands again. To save the plot, click on File  ­> Save, in the dialog that pops up, enter the name of the graph. Click on the drop ­down menus next to “Save file as: “, and choose a JPEG or PNG. Plotting Multiple Data Sets in One Graph Let try to plot multiple sin functions that are shifted to the left on the same graph: >> x = 0:pi/100:2*pi; y = sin(x); y2 = sin(x ­.25); y3 = sin(x ­.5); plot(x,y,x,y2,x,y3) legend('sin(x)','sin(x ­.25)','sin(x ­.5)') The function that we are going to use to plot this is >>plot(x,y,x,y2,x,y3) which is in the form of plot( x_values_for_first_line, y_values_for_first_line, x_values_for_second_line, y_values_for_second_line, x_values_for_third_line, y_values_for_third_line) An alternative method to add multiple plots on the same graph is to use the “hold on” command, which will add plots into the same graph until “hold off” is executed. >> x = 0:pi/100:2*pi; y = sin(x); y2 = sin(x ­.25); y3 = sin(x ­.5); plot(x,y) hold on plot(x, y2) plot(x,y3) legend('sin(x)','sin(x ­.25)','sin(x ­.5)') hold off Notice that all of the plots have the same color, instead of blue green and red. We can remedy that with line styles and colors. Line Styles and Colors Matlab allows you to specify the color, line styles, and markers when we plot using the plot command. To format a plot, use the following command: >> plot(x, y, 'color_style_marker') where ‘color_style_marker’ are chosen from the following table: For example, lets go back to our plot of the sin function: >>x = 0:pi/100:2*pi; y = sin(x); y2 = sin(x ­.25); y3 = sin(x ­.5); plot(x,y, 'b') hold on plot(x, y2, 'g') plot(x,y3, 'r') legend('sin(x)','sin(x ­.25)','sin(x ­.5)') hold off Let’s go back to our sin plot and add some styles to it: >> t = 0:pi/20:2*pi; y = sin(t); plot(t, y, 'b ­ ­^'); xlabel('X Axis') ylabel('Plot Y Axis') title('Plot of Sin(x)') The line >>plot(t, y, 'b ­ ­^'); says I want to plot t against y, with the color blue (“b”), using dashed lines (“ ­ ­“), and with filled upward triangle (“^”) as the marker. Setting Axis of the Plot Here are some other properties we can set: To specify the bounds of the axis, use: >> axis([xmin xmax ymin ymax]) To reset the axis to auto again, use: >>axis auto To set the ratio of the axis to the same length, use: >>axis square To set the individual tick mark increments on the x ­axes and y ­axes the same length, use: >>axis equal To turn on the axis, use: >>axis off To turn the axis back on, use: >>axis on To reset everything about a graph, use: >>clf reset Plotting Your Own Functions: Now let’s try to plot our SquareF function from earlier: >> x =  ­5:0.5:5; y = SquareF(x) plot(x, y, 'g ­x') xlabel('X Axis') ylabel('Plot Y Axis') title('Plot of x^2') Working with and Plotting Random Numbers: Recall from Assignment 2 where you made use of the mean() and sum() function. These functions belong to a rich set of statistical functions that Mablab provides. Here is a list of statistical functions that you should be familiar with:  ­ sum(X): add all of the elements in matrix X  ­ mean(X) : add all of the elements in matrix X and calculate the average  ­ max(X): returns the largest element in X.  ­ min(X) returns the smallest element in X.  ­ var(X): return the variance of the values of the matrix X.  ­ std(X): calculate the standard deviation of X.  ­ rand(m,n): generate a m x n matrix using uniformly distributed pseudorandom numbers(from 0 to 1).  ­ randn(m,n): generate a m x n matrix using normally distributed pseudorandom numbers(with the center at 0 and a standard deviation of 1). The difference between rand(m,n) and randn(m,n) is that the for rand(), all of the numbers in between 0 and 1 have an equally likely chance of being selected. randn() on the other hand, follows a Gaussian distribution and favors more heavily towards the center. We can visualize this by plotting the values generated with each function against the number of occurrences of each. For the rand() function: >>hist(rand(1,10000), 100) and for the randn() function: >>hist(randn(1,10000), 100) Plotting with Data From Excel Matlab allows you to import your data from a spreadsheet into your Workspace. For example, here’s my Excel file that is saved as Sample.xls: To load the data into Matlab, navigate to the current directory where the Sample.xls file is stored, and double click it: Click on Next and then Finish. The values from the Excel spreadsheet is added to the Workspace with the variable name “data”. We can then manipulate the values natively in Matlab. Plotting using a Graphical User Interface (GUI) Instead of entering commands into Matlab, a graphical user interfaces is available for plotting. To open up the GUI, type the following into the >> plottools The plotting tools are made up 4 components: 1. Plot Window: This is where your plot is displayed 2. Figure Palette: You can specify and arrange subplots, access workspace variables for plotting or editing, and add annotations 3. Plot Browser: select objects in the plot window, control visibility, and add data to axes 4. Property Editor: change key properties of the selected objects. Click “More Properties” to access all object properties Let’s try plotting our sin graph again using the GUI. First, let’s create our t and y values: >> x = 0:pi/20:2*pi; y = sin(x); Then let’s open up the GUI: >>plottools Now click on “2D Axes” under the “New Subplots” in the Figure Palette. Now click “Add Data…” on the bottom of the Plot Browser. Set the Plot Type to “plot”, the X Data Source to “x” and the Y Data Source to “y” and click “OK”. Set the label for the X Axis and the Y Axis and you are done! To save the graph, just go to File ­>Save As, and choose PNG as the save type and you are done! You can learn more about using the GUI by going to Help  ­> Product Help  ­> MATLAB  ­> Getting Started  ­> Graphics Here are some of the graphs that you can plot with Matlab: To find out more about each graph, go to: http://www.mathworks.com/help/techdoc/creating_plots/f9 ­53405.html ...
View Full Document

This note was uploaded on 11/03/2011 for the course MATH 1090 taught by Professor Greenwood during the Spring '08 term at MIT.

Ask a homework question - tutors are online