Presentation is loading. Please wait.

Presentation is loading. Please wait.

Language Basics and Data Types ● What and why of Matlab. ● Matlab desktop. ● Familiarize ourselves with basics of language. ● Basic types of data that.

Similar presentations


Presentation on theme: "Language Basics and Data Types ● What and why of Matlab. ● Matlab desktop. ● Familiarize ourselves with basics of language. ● Basic types of data that."— Presentation transcript:

1 Language Basics and Data Types ● What and why of Matlab. ● Matlab desktop. ● Familiarize ourselves with basics of language. ● Basic types of data that can be manipulated in matlab. ● More number and array stuff. ● Plotting 101. ● Saving and loading data. ● Real-world example.

2 What is Matlab? ● Matlab is a high-level computing language optimized for scientific computation and, in particular, matrix manipulation. It makes many common mathematical operations used by scientists simple and fast. ● Matlab is an interpreted language – code is compiled each time it is run. ● Matlab has excellent visualization tools.

3 Why use Matlab? ● Excellent at manipulating large amounts of tabular data (arrays, matrices) in a consistent way. The “Mat” in Matlab is for Matrix. ● Lots of built in functions for data analysis, interpolation, linear algebra, fourier analysis, visualization.... ● Add-on toolboxes for extra power. ● Mature language with GUIs, object-oriented framework.... ● Lots of independent support and free code available on the web.

4 Why not to use Matlab? ● Anything requiring repetition, for loops, tends to be slow. Limitation of interpreted language. Often solved using matrices. ● Not a statistics package. A statistics toolbox exists at a price. Much available online. ● Commercial, costly. Free imitations available (octave, scilab...), but lack some functionality. ● Well written C/FORTRAN code could be faster, but usually not worth the effort. ● Not suitable for parallel programming. Some imitations (scilab) have some ability to work in parallel.

5 Matlab Desktop

6 ● Command Window: Where commands are entered. We will principally use this area. ● Command History/Directory Listing: Useful for repeating old commands, changing directories and loading in data. ● Launch Pad: I just use it to get the hi-tech documentation going.

7 Entering Commands Here we are going to familiarize ourselves with the basics of entering commands and how to interact with matlab. Start matlab and click on the command window to make it active. Try entering the following commands:  1  1;  1+2i  a = 2  B = a * pi;  whos  clear a  whos Note that the 2 nd and 5 th lines print no output. When a command ends in ';' it works silently in matlab. Lines 4 and 5 create variables. In matlab variables do not need to be declared before use. Variable names are case sensitive. The whos command shows the variables in the workspace, their size and type. clear removes variables from the workspace.

8 Getting Help Matlab has a number of ways to get information about functions. The simplest, yet most common, is textual help from command line. Try the following:  help sqrt  more on % Let's you page text.  help *  help plot  more off The more command lets you page through output from any matlab command. Note the use of '%' to include comments. In matlab commands, anything beyond a '%' is a comment and is ignored. Matlab also has a fairly powerful help browser that children of Bill Gates will be familiar with. Try:  helpdesk You can also access much of the documentation through the launch pad. Also, try help help for more information on getting help.

9 Matlab Data Types All languages allow a variety of data types: integers, floats, booleans (T/F), strings, arrays.... Matlab is no different. However, matlab is different from C and many common languages in some important ways: ● Variables and their data types do not have to be declared beforehand. ● Matlab combines integers, floats and booleans into one thing: doubles or floating point numbers.  a = 1.54 % This is a double  b = a > 1 % Logical (boolean) double. ● Strings. Matlab treats a string as a character arrays.  b = 'abcd' % NOTE that matlab uses single quotes  b(2:3) ● Arrays/Matrices of numbers. Use ';' to separate rows, ',' or blank space to separate columns.  c = [1 2 3; 4, 5, 6] % More in next class. ● Cell Arrays. Most useful way to store several strings or mixed data.  d = { 'abcd', 1, [123], 'def' } ● Structures will de discussed in the second class.

10 Series of Numbers / Special Numbers Creating series of numbers is easy in matlab.  2:5  2:1:5  2:2:5 % Middle number is step size.  5:1  5:-1:1  5.23:0.1:7.6  pi:0.1:2*pi Note that 2:5 is shortcut for 2:1:5. Also, 5:1 produces the empty matrix as 5:1:1 makes little sense. There are also several special numbers in matlab. NaN is used for missing data. Inf and -Inf are the responses to division by zero.  a = NaN;  2 * a  1/0, -1/0 % ',' can separate commands similar to ';'  inf + -inf Capitalization is not important when using these numbers. Also, these numbers may appear in text data files without a problem.

11 Basic Array Operations I will discuss matrices in detail next week, but it is useful at this point to mention a couple simple operations.  a = [ 1 2; 3 4 ];  a(1,:) % Gets first row  a(:,1) % Gets first column  a(1,1) % Gets first element  2 * a  a * a % Matrix multiplication in the math sense  a.* a % Element-by-element Matrix multiplication  a ^ 3  a.^ 3  a.^ a % a(i,j) raised to the a(i,j) There are a number of other matrix (and otherwise) operators. Try help ops for more info. Note the difference between * and.*: * performs row*column type matrix multiplication that you will see in math textbooks;.* is equivalent to a(i,j)*a(i,j). This second form is very common in matlab and part of the reason matlab is so good at matrix manipulation.

12 Plotting 101 Matlab has extremely good visualization which could easily be an entire course. Fortunately, the simple things are simple.  a = 0:0.2:3; % Series of numbers from 0 to 3.  b = exp( a ); % exponential of those numbers  plot( a, b )  figure % Opens empty figure window.  plot( a, a, a, b )  title( 'Linear vs. Exponential Growth' )  xlabel( 'time' )  % I don't care for those colors. Lets change them.  plot( a, a, 'b', a, b, 'r-.' ) Note that the last plot command erased the previous one. This is the default, but it can be changed (see help hold). The documentation of plot explains the format strings ( 'b' and 'r-.' ) used in the last command. The appearance of figures can be changed interactively. Try clicking on the and zooming in on a part of the figure.  close all

13 Saving Data to Files Matlab allows valuable data to be saved in both text and binary formats. The binary format is a native matlab format (.mat) that allows variables to be easily saved and loaded back in later on.  clear all % Start with a clean slate.  a = ((1:100)^2)' % ' is the transpose operator  b = ((1:100)^3)'  save % Save all to matlab.mat  save a_var.mat a % Save only a in binary format  save - - ascii a_var.txt a % Save a in text format The first form of save is a quick way to save all variables into the file 'matlab.mat'. Take a look at the 'a_var.txt' file. This file could now be loaded in any spreadsheet.  open a_var.txt Finally, matlab is capable of saving all commands you enter and their output in a diary file.  diary my_diary.txt  whos  diary off  open my_diary.txt

14 Loading Data from Files Matlab loads in both binary files and tab-separated text files containing numbers.  clear all  load a_var.mat  whos % Note variable names.  load a_var.txt  whos  a2 = load('a_var.txt')  clear all  load % Loads in matlab.mat  whos Note that binary files preserve the variable names from when they were saved. When text files are loaded in, the default is create a variable with the name of the file (no extensions) containing the data. Text data files may contain matlab style comments. For example, the following is a perfectly acceptable file header: % This file was created on 2002-03-07. % yearGPA 20013.8 % A good year. 20022.1 % Who wants to be average anyway 20031.0...

15 Real-world Example Here we are going to load in some BML MOMS data and play with it. First, click here to download the data file. If the link doesn't work, take a look at the end of this page. Save the file as 'moms.txt'.  open moms.txt  load moms.txt The columns of the file are explained in the comments of the file. The column 'yearday' is the number of days since 2001-01-01. It is useful for temporal plots. The exercise for this class is to first make a plot of time vs. temperature. Make sure to add a title and some axis labels so I know what you are plotting. Next calculate the the NS component of the wind stress. For our purposes, the formula for NS wind stress is where u and v are the components of the wind velocity. Next, plot time vs. v-wind stress on a new figure. Include a zero line to ease visualization. Compare the two figures and note that temperature increases when wind stress is negative (from the South). Don't worry if you don't get it. The solution is on the next slide.

16 Solution  load moms.txt  plot(moms(:,4), moms(:,5))  title('Water Temperature for BML, 2001')  xlabel( 'Day of the Year' )  ylabel( 'Temperature (^{o}C)' )  figure  wind_speed = sqrt( moms(:,6).^2 + moms(:,7).^2 );  ns_wind_stress = moms(:,7).* wind_speed;  plot( moms(:,4), ns_wind_stress,...  moms(:,4), 0 * moms(:,4) )  %%... is used to continue lines. %%%  title( 'NS Wind Stress for BML, 2001' )  xlabel( 'Day of the Year' )  ylabel( 'NS Wind Stress' )


Download ppt "Language Basics and Data Types ● What and why of Matlab. ● Matlab desktop. ● Familiarize ourselves with basics of language. ● Basic types of data that."

Similar presentations


Ads by Google