To look at the importance of the ‘.’ Go back to our matrix C1 C1=([2 1 4; 4 3 6; 6 8 2]) Now try to multiply C1 by C1 MESHGRID – spans a grid where points.

Slides:



Advertisements
Similar presentations
Matlab Intro Simple introduction to some basic Matlab syntax. Declaration of a variable [ ] Matrices or vectors Some special (useful) syntax. Control statements.
Advertisements

Lecture 5.
Matlab Graphics S. Awad, Ph.D. M. Corless, M.S.E.E. E.C.E. Department University of Michigan-Dearborn Introduction to Matlab: 2D Graphics.
M AT L AB Programming: scripts & functions. Scripts It is possible to achieve a lot simply by executing one command at a time on the command line (even.
Introduction to MATLAB for Biomedical Engineering BME 1008 Introduction to Biomedical Engineering FIU, Spring 2015 Lesson 2: Element-wise vs. matrix operations.
Chapter 11 Above: Principal contraction rates calculated from GPS velocities. Visualized using MATLAB.
DATA RETRIEVAL AND GUI CREATION DAVID COOPER SUMMER 2014.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 19P. 1Winter Quarter MATLAB: Script and.
By Hrishikesh Gadre Session II Department of Mechanical Engineering Louisiana State University Engineering Equation Solver Tutorials.
Graphics in MATLAB Week 15 – 5/5/09 Kate Musgrave
1 Introduction to MatLab MatLab stands for Matrix Laboratory. As the name suggests most of the programming operations have as input or output a matrix.
Division Example 2x - 3y + 4z = 10 x + 6y - 3z = 4 -5x + y + 2z = 3 A*X = B where A = B = >> X = A\B X =
Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group
Introduction to MATLAB Northeastern University: College of Computer and Information Science Co-op Preparation University (CPU) 10/29/2003.
Fall 2006AE6382 Design Computing1 Matlab File & Directory Management Learning Objectives Define file input and output terminology Compare high and low.
Introduction to MATLAB MECH 300H Spring Starting of MATLAB.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Extending MATLAB Write your own scripts and/or functions Scripts and functions are plain text files with extension.m (m-files) To execute commands contained.
MATLAB Fundamentals.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
Chapter 5 Review: Plotting Introduction to MATLAB 7 Engineering 161.
Introduction to MATLAB
Objectives Understand what MATLAB is and why it is widely used in engineering and science Start the MATLAB program and solve simple problems in the command.
1 Tips for solving Project 1 Reactor SO 3 SO 2 +O 2.
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
GUI development with Matlab: GUI Front Panel Components 1 GUI front panel components In this section, we will look at -GUI front panel components -Programming.
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
Introduction to File I/O High-Level Functions 1.Data files 2."High level" File I/O 3.dlmread() 4.xlsread() 1.
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
MA/CS 3751 Fall 2002 Lecture 24. MA/CS 3752 ginput ginput is a Matlab function which takes one argument input: number of points to select in the image.
Matlab Programming for Engineers Dr. Bashir NOURI Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Lecture 2 - Matlab Introduction CVEN 302 June 5, 2002.
1 Input / Output Input – reads/gets data for the program Output – the product, after processing Both can be: interactive I/O (while program is running)
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
ENG College of Engineering Engineering Education Innovation Center 1 More Script Files in MATLAB Script File I/O : Chapter 4 1.Global Variables.
MATLAB – PT1 The purpose of this workshop is to get you started and to have fun with MATLAB! Let’s talk a little and decide on what we will be covering.
Recap Plots with More than one Line Plots of Complex Arrays Line, Color and Mark Style Axis Scaling and Annotating Plots Subplots Polar Plots Logarithmic.
Files: By the end of this class you should be able to: Prepare for EXAM 1. create an ASCII file describe the nature of an ASCII text Use and describe string.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Files Tutor: You will need ….
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
1 Faculty Name Prof. A. A. Saati. 2 MATLAB Fundamentals 3 1.Reading home works ( Applied Numerical Methods )  CHAPTER 2: MATLAB Fundamentals (p.24)
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Introduction to Programming on MATLAB Ecological Modeling Course Sep 11th, 2006.
An Introduction to Programming in Matlab Emily Blumenthal
Beginning Programming for Engineers Animation. Special matrix functions >> clear >> ones(2,3) >> zeros(3,5) >> ones(2) >> zeros(3) >> eye(4) >> magic(4)
MAE 421 Matlab review Prof. Mark Glauser Created by: David Marr.
How to use MATLAB (using M-files) Double click this icon To start Matlab 6.5.
OTGA UEM RTC Introdução ao Matlab: introdução de dados, batimetria, linhas de contorno, traçar diagramas e perfis 24 Janeiro 2017 Fialho Nehama, UEM-ESCMC,
Release Numbers MATLAB is updated regularly
Examples, examples: Outline
Matlab Training Session 4: Control, Flow and Functions
Lecture 25.
MATLAB DENC 2533 ECADD LAB 9.
Advanced Data Import & Export Jeff Henrikson
MATLAB How to use (using M-files) Double click this icon
MATLAB Tutorial Dr. David W. Graham.
MATLAB How to use (using M-files) Double click this icon
MatLab – 2D Plots 2 MATLAB has many built-in functions and commands to create various types of plots. Instructor notes: We start with an example of some.
MATLAB How to use (using M-files)
Matlab Training Session 5: Importing Data
funCTIONs and Data Import/Export
Note on Indexing of Array Elements
Introduction to MATLAB
Presentation transcript:

To look at the importance of the ‘.’ Go back to our matrix C1 C1=([2 1 4; 4 3 6; 6 8 2]) Now try to multiply C1 by C1 MESHGRID – spans a grid where points in a 2D matrix are assigned X and Y positions (or X, Y, Z for 3D) EG, we want to calculate the cosine XbyY on an area limited by X=+-3 and Y=+-3. Make the grid: >>[X,Y]=meshgrid(-3:.1:3,-3:.1:3) >>figure(1); Z=X.*Y; surf(X,Y,Z); colorbar %%%plots 3D figure and adds a %%colorbar >>figure; Z=X.*Y; contourf(X,Y,Z); %%%2D figure filled contours >>figure; Z=X.*Y; contour(X,Y,Z); %%%2D figure not filled contours >> figure(2); Z=cos(X.*Y); surf(X,Y,Z);

Control flow of data….. for i=1:10, if i<5 a(i)=i*2; elseif i==5 a(i)=i; else a(i)=i/2; end; end for i=10:15 counter=counter+1 if i<15 a(counter)=i*2; elseif i==15 a(counter)=i; end

>>while i>5; >>a(i)=i*2; >>i=i-1; >>end

1)Create a vector X with values from 0 to 100 at intervals of 0.1 a)What is the 20 th prime number in X b)How many prime numbers are less than 1million c)Factorize (i.e. find the sequence of prime numbers resulting in this number when multiplied together) 2)Create the vector X=[ ] This is actually a message as each number represents a character or symbol. Matlab uses ASCII coding and every character is assigned a value between 0 and 255. a)Which sentence is represented by X? b)What is the ascii code for ‘enter’ c)Using findstr what is the position of r in the above text?

X=[0:0.1:100]; t=primes(100); t(20) t2=primes( ); size(t2) f=factor( ); x=[ ]; s=char(x); double('enter'); findstr(x,'r')

Often need to work with 3 or 4 D matrices, such as global atmosphere data or model generated data. Here is an example where we create a 3D space spanned by axes X,Y and Z. The first axis has values 0 to 360 with steps of 20. The second axis -90 to 90 with steps of 20 and finally an axis from 1990 to with steps of 1/12: >>[X,Y,Z]=meshgrid(0:20:360,-90:20:90,1990:1/12: ); Generate the data……. >>data=sin(X/1000).*cos(Y/100).*tanh(Z/2000);

a) What is the size of the matrix data? What is the minimum, maximum and mean value. In what position is the maximum? b) Assume that the first 2 dimensions represent long and lat and the third is time and that the data are a scalar field eg global mean temps for a decade. How can you calculate the mean for each year? c) It is common to make anomalies of data (deviation from the climate mean) by removing the mean for every month. i.e for every january we remove the mean of all the january months in the data (hear we have 10). Jananom1999=janvalue1999-janmean( ); plot the July anomaly for 1995 (help contour)

>> size(data) ans = >> min(data(:)) ans = 0 >> max(data(:)) ans = >> mean(data(:)) ans =

>>[val,ind]=max(data(:)) >>[a,b,c,]=ind2sub(size(data),ind) >>data2=reshape(data,10,19,12,10); >>size(data2) >>for y=1:10; >>Yr_data=squeeze(data2(:,:,:,y)); >>Yr_data2(:,:,y)=mean(Yr_data,3); >>end >>for m=1:12; >>mn_data=squeeze(data2(:,:,m,:)); >>mn_climo(:,:,m)=mean(mn_data,3); >>end >>for m=1:12; >> for yr=1:10 >> Mn_anom(:,:,m,yr)=squeeze(data2(:,:,m,yr))- squeeze(mn_climo(:,:,m)); >> end

Reading ascii data w/o header Example ctd >> clear all >> load examplectd.dat Whos – examplectd in workspace which is 2138x5 Ignores spaces. But if data is separated by comma and NO SPACE, have to use function dlmread – data=dmlread(‘filename’,’,’); ALSO, if file has no extension have to include –ascii when loading….. >>load ‘filename’ –ascii Now, to split into variables: >>depth=examplectd(:,1); temp=examplectd(:,2); salinity=examplectd(:,3); oxygen=examplectd(:,4); fluro=examplectd(:,5);

figure subplot(1,4,1);plot(temp,-depth); subplot(1,4,2);plot(salinity,-depth); subplot(1,4,3);plot(oxygen,-depth); subplot(1,4,4);plot(fluro,-depth); figure,plot(salinity,temp) title('salinity temp plot from BATS') xlabel('salinity') ylabel('temperature') legend

Ascii-data with boring header Use the function textread >> [cruise,decimal,lat,lon,press,depth,temp]=textread('example ctdtxt.dat','%f %f %f %f %f %f %f','headerlines',2); If csv >> [cruise,decimal,lat,lon,press,depth,temp]=textread('example ctdtxt.dat','%f %*s %f %*s %f %*s %f %*s %f %*s %f %*s %f','headerlines',2); The sign %* ensures that the data are not returned by the function. The last part of the command ‘headerlines’,2 tells matlab to ignore the first 2 lines

Ascii-data with interesting header >>fid=fopen(‘examplectdtxt.dat’,’r’); >>dummy=fread(fid,’char’); >>fclose(fid); First we open file for reading (‘r’ is short for read). And a file identification number is given to fid. 2 nd line, we read all the data as ascii code (numbers between 0 and 127) and then on 3 rd line we close the file.

So we have now retrieved data and stored as numbers >> char(dummy(1:1400)') Converts ascii code to characters. Note the ‘ transpose. With whos you can see that dummy is a 86069x1 matrix (column vector). So to print data to look like in a text editor, need to transpose to 1x86069.

Now we want to extract information from the header: year, lat and lon. Convert dummy into a row of characters >> c=char(dummy'); Then use findstr to find the positions of the variables we want >>temp_index=findstr('(C)',c); >>ctd=str2num(c(temp_index+3:end));

saving ascii-data the opposite function of load is save >>load examplectd.dat; >>save 'C:\Documents and Settings\juliet\ctd.asc' -ascii; if –ascii is not included, matlab will save as a.mat file, which is fine for use in matlab but not anything else. the new file is twice as large as the old one as matlab saves in a different format (look at two files). To separate data with column… >>dlmwrite('ctd2.asc',examplectd,','); This is more compressed, but can be slow. A more readable form can be made using the fprintf function. Similar to textread

load 'examplectd.dat' >> fid=fopen('ctd3.asc','wt') >> fprintf(fid,'%4d %6.3f %6.3f %6.2f %5.3f\n',examplectd'); >> fclose(fid)

>>load 'examplectd.dat' >>depth=examplectd(:,1); temp=examplectd(:,2); >>salinity=examplectd(:,3); oxygen=examplectd(:,4); >>fluro=examplectd(:,5); The figure window is at the top of the heirachy! There are 62 parameters controlling the figure window. 2 commands used to change the settings: get and set >>figure, plot(temp,-depth) >>get(1) OR get(gcf) where gcf=get current figure.

The third parameter is Color = [0 0 0] telling us that the color of the figure is black >>get(gcf,’color’); change the color by setting parameter >>set(gcf,’color’,[ ]) >>set(gcf,’name’,’ctd1 temp’); %%puts name on fig >>set(gcf,position’,[ ]); %can also use mouse!

axes also have properties – 90 but now have to get all of the axis properties: >>get(gca) If you want red instead of black axis window: >>set(gca,’color’,[1 0 0]); %%%%other parameters to adjust: >>set(gca,’fontangle’,’italic’) >>set(gca,’fontsize’,15) >>set(gca,’linewidth’,2) >>set(gca,’position’,[ ]) >>set(gca,’xcolor’,[0 0 1]) >>set(gca,’xlim’,[1 24]) >>set(gca,’xtick’,[1:5:24]) >>set(gca,'xticklabel',['01C';'06C';'11C';'16C';'21C'])

can do many at the same time: >> set(gca,'fontangle','italic','fontsize',15,'linewidth',2,'xgrid','on') Adding text: >> title('ctd temperature plot') >> xlabel('temperature') >> ylabel('Depth (m)') >> gtext('18C water') %%puts the text where you click on fig also the functions: grid on and grid off hold on and hold off

>> load 'ADCP.txt' -ascii >> direction=ADCP(:,1); >> VelE=ADCP(:,2); >> VelN=ADCP(:,3); >> VelU=ADCP(:,4); >> figure,plot(VelU) >> figure,plot(VelE) >> figure,plot(VelN) other plotting options: polar, rose and feather in matlab the direction is needed in radians, and often the direction is given relative to north…… to find the direction in radians: >>theta=(90-direction)*pi/180;

>> load('SST_IO') >> whos >> climoSST=squeeze(mean(SST)); >> for mn=1:12; SSTanom(mn,:,:)=squeeze(SST(mn,:,:))-climoSST; end %%now we want to plot some contoured figures >>temprange=[20:0.5:30] %%defines the contours we’ll plot >>for mn=1:12 subplot(3,4,mn) contourf(lon,lat,squeeze(SST(mn,:,:)),temprange) caxis([20 30]); %%%defines the limits of the colorbar end >>colorbar

Or maybe we just want to plot a figure showing the annual mean and we want to interpolate >> figure >> pcolor(lon,lat,climoSST);shading interp >> colorbar %%%%%then we want to plot contourf lines on top for 25C >> hold on >> [cs,h]=contour(lon,lat,climoSST,[ ],'w'); %%[cs,h] is a way %of giving the contour lines a ‘handle’ in order to label them >>clabel(cs,’manual’);

%now lets look at the anomalies >>temprange=[-10:0.2:10] %%defines the contours we’ll plot >>for mn=1:12 subplot(3,4,mn) contourf(lon,lat,squeeze(SSTanom(mn,:,:)),temprange) caxis([-2 2]); %%%defines the limits of the colorbar end >>colorbar look at times series over IO >> anom1=squeeze(nanmean(SSTanom,2)); %%use nanmean as %there are NaN values as a landmask >> anomIO=squeeze(nanmean(anom1,2)); >> figure,plot(anomIO)

%%%Do some simple correlations, so create a similar time- series for the atlantic (a bit nonsensical but then you get the correlation programs!!!) >> AO_anom=tan(anomIO); >> figure,plot(AO_anom), hold on,plot(anomIO,’:’)

y1=AO_anom;y2=anomIO; %%input variables clear brol1 brol2 r1 r2 tau eodf r_95 prob t n r;%%%clear specific variables (if run this before) r=corrcoef(y1,y2);%%%%calcluate correlation [c,lags]=xcorr(y1,y2,'coeff');%%%calculate correlation at different time lags between data if (abs(min(c))>=max(c));%%find if the max correlation is positive or negative r=min(c),[x,y]=min(c); else; r=max(c),[x,y]=max(c); end n=length(y1); %%%%%%%% k=n/2; %%%%%%%% for i=1:k; brol1=corrcoef(y1(1:n-i),y1(i+1:n)); brol2=corrcoef(y2(1:n-i),y2(i+1:n)); r1(i)=brol1(1,2); r2(i)=brol2(1,2); end; tau=[1+2*sum(r1.*r2)]; eodf=round(n/tau); r_95=1.96/sqrt(eodf-2)%%%correlation at.95 confidence r_99=2.33/sqrt(eodf-2)%%%correlation at.99 confidence t= abs(r/sqrt((1-r*r)/(eodf-2))); df=eodf-2; %prob_directional=tcdf(t,df) %prob_non_directional=1-(1-prob_directional)*2 r%correlation, is it significant at the.95 or.99 level? lags(y)%% time lag (based on the timesteps of data set, if -ve then y2 leads y1

%%%%help m_map – built in toolbox which allows you to plot on different projections (useful if looking at large areas). Also has built in topography and coastlines etc