+ All Categories
Home > Documents > Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics...

Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics...

Date post: 30-Sep-2020
Category:
Upload: others
View: 1 times
Download: 0 times
Share this document with a friend
16
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.
Transcript
Page 1: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

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 inmatlab.

� More number and array stuff.

� Plotting 101.

� Saving and loading data.

� Real �world example.

Page 2: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

What is Matlab?

� Matlab is a high �level computing languageoptimized for scientific computation and, inparticular, matrix manipulation. It makes manycommon mathematical operations used byscientists simple and fast.

� Matlab is an interpreted language – code iscompiled each time it is run.

� Matlab has excellent visualization tools.

Page 3: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Why use Matlab?

� Excellent at manipulating large amounts of tabulardata (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 �orientedframework ....

� Lots of independent support and free codeavailable on the web.

Page 4: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Why not to use Matlab?

� Anything requiring repetition, for loops, tends tobe slow. Limitation of interpreted language. Oftensolved using matrices.

� Not a statistics package. A statistics toolbox existsat 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. Someimitations (scilab) have some ability to work inparallel.

Page 5: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Matlab Desktop

Command Window

Launch Documentation

Command Historyand Directory Listing

Page 6: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Matlab Desktop

� Command Window: Where commands areentered. We will principally use this area.

� Command History/Directory Listing: Usefulfor repeating old commands, changing directoriesand loading in data.

� Launch Pad: I just use it to get the hi �techdocumentation going.

Page 7: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Entering CommandsHere we are going to familiarize ourselves with the basics of entering commandsand how to interact with matlab. Start matlab and click on the command window tomake it active. Try entering the following commands:

» 1

» 1;

» 1+2i

» a = 2

» B = a * pi;

» whos

» clear a

» whos

Note that the 2nd and 5th lines print no output. When a command ends in ';' it workssilently in matlab.

Lines 4 and 5 create variables. In matlab variables do not need to be declared beforeuse. Variable names are case sensitive.

The whos command shows the variables in the workspace, their size and type.clear removes variables from the workspace.

Page 8: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Getting HelpMatlab has a number of ways to get information about functions. The simplest, yetmost 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. Notethe use of '%' to include comments. In matlab commands, anything beyond a '%' is acomment and is ignored.

Matlab also has a fairly powerful help browser that children of Bill Gates will befamiliar with. Try:

» helpdesk

You can also access much of the documentation through the launch pad. Also, tryhelp help for more information on getting help.

Page 9: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Matlab Data TypesAll 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 manycommon 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 floatingpoint 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 separatecolumns.

� 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.

Page 10: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Series of Numbers / Special NumbersCreating 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:1makes little sense.

There are also several special numbers in matlab. NaN is used for missing data. Infand �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 mayappear in text data files without a problem.

Page 11: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Basic Array OperationsI will discuss matrices in detail next week, but it is useful at this point to mention acouple 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 formore info.

Note the difference between * and .*: * performs row*column type matrixmultiplication 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 goodat matrix manipulation.

Page 12: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Plotting 101Matlab 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( ' Li near vs. Exponential Gr owt h' )

� xlabel( ' t i me' )

� % 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 itcan be changed (see help hold).

The documentation of plot explains the format strings ( 'b' and 'r �.' ) used in thelast command.

The appearance of figures can be changed interactively. Try clicking on the andzooming in on a part of the figure.

� close all

Page 13: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Saving Data to FilesMatlab allows valuable data to be saved in both text and binary formats. The binaryformat is a native matlab format (.mat) that allows variables to be easily saved andloaded 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 adiary file.

� diary my_diary.txt

� whos

� diary off

� open my_diary.txt

Page 14: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Loading Data from FilesMatlab 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 = l oad( ' a_var . t xt ' )

� clear all

� load % Loads in matlab.mat

� whosNote 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 thefile (no extensions) containing the data.

Text data files may contain matlab style comments. For example, the following is aperfectly acceptable file header:

% This file was created on 2002 �03 �07.% year GPA2001 3.8 % A good year.2002 2.1 % Who wants to be average anyway2003 1.0...

Page 15: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Real �world ExampleHere we are going to load in some BML MOMS data and play with it. First, clickhere to download the data file. If the link doesn't work, take a look at the end of thispage. Save the file as 'moms.txt'.

� open moms.txt

� load moms.txtThe 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 sureto add a title and some axis labels so I know what you are plotting. Next calculatethe the NS component of the wind stress. For our purposes, the formula for NSwind 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 easevisualization. Compare the two figures and note that temperature increases whenwind stress is negative (from the South).

Don't worry if you don't get it. The solution is on the next slide.

w � v u 2 �

v2

Page 16: Language Basics and - pmc.ucsc.edudmk/old-matlab-mini-course/notes_download… · Language Basics and Data Types What and why of Matlab. Matlab desktop. Familiarize ourselves with

Solution

� load moms.txt

� plot(moms(:,4), moms(:,5))

� t i t l e( ' Wat er Temperature for BML, 2001' )

� xlabel( ' Day of the Year ' )

� ylabel( ' Temper at ur e ( ^ { 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 St r ess' )


Recommended