Presentation is loading. Please wait.

Presentation is loading. Please wait.

John Federici NJIT Physics Department

Similar presentations


Presentation on theme: "John Federici NJIT Physics Department"— Presentation transcript:

1 John Federici NJIT Physics Department
Physics 114: Lecture 2 More MatLAB Making plots, using functions Using HELP APPLICATION: Write a basic MatLAB program to plot generated data Defining Functions – Homework Submissions of MATLAB CODE John Federici NJIT Physics Department

2 TRIVIA QUESTION! Who sings the theme song for the “Big Bang Theory”?
(a) Numeriklab (b) Ramin Djawadi (c) Justin Bieber (d) Barenaked Ladies (e) Joakim Lindström

3 TRIVIA QUESTION! Who sings the theme song for the “Big Bang Theory”?
(a) NCIS - Numeriklab (b) Ramin Djawadi - Game of Thrones (composer) (c) Justin Bieber – The Karate Kid (d) Barenaked Ladies – BIG BAND THEORY (e) Joakim Lindström – The Walking Dead theme

4 The Basics of Plotting Data
Within MATLAB, lets create some data and plot the data Indexing of Arrays Generating Functions Plot Function Row Column >> A(4,5)=17 A = >> NOTE: Arrays are UNITY index based… First element is 1, 2nd element is 2, etc. Row Column

5 Indexing of Arrays You can select sub elements (or define sub-elements) of an array using the “:” operator as in start:end of a range A “wild card” meaning everything in the available range A = >> A(1,1:3) ans = Row 1, first THROUGH 3nd Column elements >> A(:,1)=0 A = Set EVERY element in Column 1 to be zero

6 Indexing of Arrays You can also combine all elements of a 2D array into a 1D array. This manipulation is helpful later on in the course when we will statistically analyze 2D data. For example, images… Excellent reference for indexing of arrays: >> A(:) ans = 1 2 3 “:” operator converts the multidimentional array into a VECTOR A =

7 Indexing of Vectors You easily define equally spaced vectors. This is handy for defining an ‘index’ vector or for defining an “x axis” variable of fixed spacing. >> i=1:10 i = Default “step size” of 1 >> time=0:15:100 time = Time values starting at zero, incrementing by 15 For each element upto last element equal to or less than 100

8 The Basics of Plotting Data
Within MATLAB, lets create some data and plot the data Indexing of Arrays Generating Functions Plot Function MATLAB® provides a large number of functions that perform computational tasks. Functions are equivalent to subroutines or methods or Sub-VIs in other programming languages. If you more or less know WHAT function you need to perform, you can use the HELP search documentation within MATLAB. As an example, how do we find the MAXIMUM value in an array?

9 Submitting ‘max’ in documentation help

10 Generate a Plot with a Function
>> x=-1:.01:1; >> y=sinc(x); >> plot(x,y) >> Define x variable between -1 and 1 with 0.01 step size Sinc function is Sin(x)/x Plot x versus y Matlab will open up a new window to plot the data such as on the left. Under the EDIT tab, you can copy the figure to the clipboard and PASTE into WORD, PPT, etc. You can also save the plot in a variety of formats

11 What is WRONG with this figure?

12 What is WRONG with this figure?
2D plots MUST have labels on each axis If the numbers on x or y axis are NOT dimensionless, they MUST have units. Arbitrary Units? Perhaps you need a TITLE… Is this figure for a paper in which there is a figure caption? Is the figure for a presentation? If more than one ‘curve’ of data, is there a legend to tell the data sets apart? Go into Matlab, search on ‘plot’ and see all of the options for changing color, line type (eg. dash-dot), marker symbol through the LineSpec parameter.

13 Adding labels and legend
>> x=-1:.01:1; >> y=sinc(x); >> plot(x,y) >> xlabel('time (s)') >> ylabel('Voltage (mV)') >> legend('fake data by Prof. Federici') >> You can also edit these parameters, as well as others such as limits of axes, fonts, etc. from WITHIN the figure window in MATLAB. Open the EDIT tab and choose Axis Properties…. You can change figures PROGRAMATICALLY through the command window OR via the EDIT tab…. LEFT click on curve to select. Then RIGHT click to EDIT… Then under FILE choose GENERATE CODE

14 Changing Linestyle and Linewidth
Demonstrate using EDIT FIGURE tab of FIGURE window, changing linetype time, color and width. Demonstrate using EDIT AXES tab changing Font size and color for different Axes. Click on MORE PROPERTIES and change LINEWIDTH of axes. Use the following code to change the linewidth of AXES programatically >> ax=gca; % retreives the current Axes style information >> ax.LineWidth = 5; % sets the linewidth of the axes to 5 pts

15 Command Line programming or Graphical User Interface (GUI)?
You can also edit these parameters, as well as others such as limits of axes, fonts, etc. from WITHIN the figure window in MATLAB. Open the EDIT tab and choose Axis Properties…. You can change figures PROGRAMATICALLY through the command window OR via the EDIT tab Class discussion: Under what circumstances would you analyze data via LINE BY LINE processing in the command window OR via the GUI interface?

16 Cartoon break….

17 Adding Multiple Curves to a Plot
>> x=-1:.01:1; >> y=sinc(x); >> z=sin(x-0.5); >> plot(x,y) >> hold on >> plot(x,z) >> hold off >> Plot x versus y “hold” plot so it does not erase with next plot command Plot x versus z “hold” off, so next plot command will overwrite the graphs. >> xz(1,:)=y; >> xz(2,:)=z; >> plot(x,xz) Alternatively, you can assign each ROW in an array to be the ‘y-axis’ data. Note: x-axis data for both curves must be same.

18 3D plots 3D plots are similar in syntax to generating 2D plots.
Conceptually, you create a ‘grid’ of xi values which are used by function “f” to generate the corresponding yi values. For 3D plots, the same concept applies EXCEPT we need a 2D grid of xi and yj values meshgrid function [X,Y] = meshgrid(xgv,ygv) [X,Y,Z] = meshgrid(xgv,ygv,zgv) [X,Y] = meshgrid(gv) [X,Y,Z] = meshgrid(gv)

19 3D plots >> [x,y]=meshgrid(-2:.2:2); >> z=exp(-x.^2-y.^2);
>> surf(x,y,z) WHY do you need the “.” before the “^” in the formula?

20 Course Policy on Submitting Matlab Code:
If for any homework problem (eg. HW#2) or class project that requires you to submit Matlab code please use one of the following options: Make sure that the location of any input files is included in the file path in which Matlab searches (use PATHTOOL command in Matlab). (b) The submitted code via must be ‘stand-alone’. This means that if your instructor copies and pastes your code into Matlab it should run WITHOUT any errors. To ensure that this is true, when you download any data files from the course web page which will be imported into Matlab, DO NOT change the name(s) of any input files. Examples…..

21 Example of Standalone Code
>> y=sinc(x); >> plot(x,y) >> xlabel('time (s)') >> ylabel('Voltage (mV)') >> legend('fake data by Prof. Federici')

22 Example of Import Data - Standalone Code
>> IMdata=imread('Lecture4-Cartoon.jpg'); >> colormap gray(256) >> grayout=rgb2gray(IMdata); >> image(grayout) >> colorbar Name of file from course webpage As long as the file is in the PATH (use PATHTOOL command to set) of Matlab, this will be a ‘stand-alone’ code. You DO NOT need to include the exact path to the filename in the Matlab code.

23 Course Policy on Submitting Matlab Code:
If you define any Matlab functions which are required for your code to run, you must include the functions as a Matlab file as an attachment to your homework. (d) Prior to submitting your HW assignment or other Matlab assignments, you should VERIFY that your Matlab code will run WITHOUT any execution errors. Example….

24 Defining a function Output parameters Input parameters
function [y]=JffQuad(x,a,b,c) % MAKE SURE YOU ADD COMMENTS TO DOCUMENT YOUR FUnction! % evaluates quadradic polynomial % input parameters % a - coefficient of quadratic term % b - coefficient of linear term % c - constant offset term % % Output parameters % y given by y=a*x^2+b*x+c y=a.*x.^2+b.*x+c; end Save this Matlab code as JffQuad.m

25 Defining a function Define Input parameters Call the Function
>> x=-5:0.02:5; >> a=1; b=2; c=3; >> y=JffQuad(x,a,b,c); >> plot(x,y) Call the Function

26 Course Policy on Submitting Matlab Code:
(d) Prior to submitting your HW assignment or other Matlab assignments, you should VERIFY that your Matlab code will run WITHOUT any execution errors. After you save your scripts, make sure that code will run Clear WORKSPACE variables Make sure that FUNCTION file is in Matlab path Run main code or script. If you generate an “error” in running Matlab code, FIX IT! >> x=-5:0.02:5; >> a=1; b=2; c=3; >> y=JffQuad(x,a,b,c); >> plot(x,y) In submitting your HW, you need to include as attachments ANY functions which you define.

27 Examples from Student Submissions
Student example which RUNS Student example which DOES NOT RUN

28 Class Exercise: Write a Simple Matlab program
Use Matlab HELP or DOCUMENTATION SEARCH as needed Create a MATLAB program which Defines the ‘x’ range from 0 to 20. Divide this range into roughly 100 equally spaced intervals. Create data using the following function: y=sin(x) Create data using the following function: z=cos(x) Create data using the following function: a=sin(x) cos(x) Create a plot of y, z, and a versus x all on the same graph. Each curve should be a different color (say Red, Blue, and Black)


Download ppt "John Federici NJIT Physics Department"

Similar presentations


Ads by Google